-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
json.ts
62 lines (52 loc) 路 1.73 KB
/
json.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
import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';
import type { ColumnBaseConfig } from '~/column.ts';
import { entityKind } from '~/entity.ts';
import type { AnyPgTable } from '~/pg-core/table.ts';
import { PgColumn, PgColumnBuilder } from './common.ts';
export type PgJsonBuilderInitial<TName extends string> = PgJsonBuilder<{
name: TName;
dataType: 'json';
columnType: 'PgJson';
data: unknown;
driverParam: unknown;
enumValues: undefined;
}>;
export class PgJsonBuilder<T extends ColumnBuilderBaseConfig<'json', 'PgJson'>> extends PgColumnBuilder<
T
> {
static readonly [entityKind]: string = 'PgJsonBuilder';
constructor(name: T['name']) {
super(name, 'json', 'PgJson');
}
/** @internal */
override build<TTableName extends string>(
table: AnyPgTable<{ name: TTableName }>,
): PgJson<MakeColumnConfig<T, TTableName>> {
return new PgJson<MakeColumnConfig<T, TTableName>>(table, this.config as ColumnBuilderRuntimeConfig<any, any>);
}
}
export class PgJson<T extends ColumnBaseConfig<'json', 'PgJson'>> extends PgColumn<T> {
static readonly [entityKind]: string = 'PgJson';
constructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgJsonBuilder<T>['config']) {
super(table, config);
}
getSQLType(): string {
return 'json';
}
override mapToDriverValue(value: T['data']): string {
return JSON.stringify(value);
}
override mapFromDriverValue(value: T['data'] | string): T['data'] {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch {
return value as T['data'];
}
}
return value;
}
}
export function json<TName extends string>(name: TName): PgJsonBuilderInitial<TName> {
return new PgJsonBuilder(name);
}