-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
Type.ts
85 lines (68 loc) · 2.38 KB
/
Type.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Platform } from '../platforms';
import type { Constructor, EntityMetadata, EntityProperty } from '../typings';
export interface TransformContext {
fromQuery?: boolean;
key?: string;
mode?: 'hydration' | 'query' | 'discovery' | 'serialization';
}
export abstract class Type<JSType = string, DBType = JSType> {
private static readonly types = new Map();
meta?: EntityMetadata;
prop?: EntityProperty;
/**
* Converts a value from its JS representation to its database representation of this type.
*/
convertToDatabaseValue(value: JSType | DBType, platform: Platform, context?: TransformContext | boolean): DBType {
return value as DBType;
}
/**
* Converts a value from its database representation to its JS representation of this type.
*/
convertToJSValue(value: JSType | DBType, platform: Platform): JSType {
return value as JSType;
}
/**
* Converts a value from its JS representation to its database representation of this type.
*/
convertToDatabaseValueSQL?(key: string, platform: Platform): string;
/**
* Modifies the SQL expression (identifier, parameter) to convert to a JS value.
*/
convertToJSValueSQL?(key: string, platform: Platform): string;
/**
* How should the raw database values be compared? Used in `EntityComparator`.
* Possible values: string | number | boolean | date | any | buffer | array
*/
compareAsType(): string {
return 'any';
}
/**
* Converts a value from its JS representation to its serialized JSON form of this type.
* By default uses the runtime value.
*/
toJSON(value: JSType, platform: Platform): JSType | DBType {
return value;
}
/**
* Gets the SQL declaration snippet for a field of this type.
*/
getColumnType(prop: EntityProperty, platform: Platform): string {
return prop.columnTypes?.[0] ?? platform.getTextTypeDeclarationSQL(prop);
}
static getType<JSType, DBType = JSType>(cls: Constructor<Type<JSType, DBType>>): Type<JSType, DBType> {
const key = cls.name;
if (!Type.types.has(key)) {
Type.types.set(key, new cls());
}
return Type.types.get(key);
}
/**
* Checks whether the argument is instance of `Type`.
*/
static isMappedType(data: any): data is Type<any> {
return !!data?.__mappedType;
}
}
Object.defineProperties(Type.prototype, {
__mappedType: { value: true, enumerable: false, writable: false },
});