aboutsummaryrefslogtreecommitdiff
path: root/src/lib/models/__helpers.ts
blob: 049dc004972dc567fb1d377eca5446dd396872b2 (plain)
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
import { type Model } from 'sequelize';

const { DataTypes } = (await import('sequelize')).default;

export function jsonParseGet(this: Model, key: string): any {
	return JSON.parse(this.getDataValue(key));
}
export function jsonParseSet(this: Model, key: string, value: any): any {
	return this.setDataValue(key, JSON.stringify(value));
}

export function jsonObject(key: string): any {
	return {
		type: DataTypes.TEXT,
		get: function (): Record<string, unknown> {
			return jsonParseGet.call(this, key);
		},
		set: function (val: Record<string, unknown>) {
			return jsonParseSet.call(this, key, val);
		},
		allowNull: false,
		defaultValue: '{}'
	};
}

export function jsonArray(key: string, defaultValue: string[] = []): any {
	return {
		type: DataTypes.TEXT,
		get: function (): string[] {
			return jsonParseGet.call(this, key);
		},
		set: function (val: string[]) {
			return jsonParseSet.call(this, key, val);
		},
		allowNull: false,
		defaultValue: JSON.stringify(defaultValue)
	};
}

export function jsonBoolean(key: string, defaultVal = false): any {
	return {
		type: DataTypes.STRING,
		get: function (): boolean {
			return jsonParseGet.call(this, key);
		},
		set: function (val: boolean) {
			return jsonParseSet.call(this, key, val);
		},
		allowNull: false,
		defaultValue: `${defaultVal}`
	};
}

export function jsonBigint(key: string, defaultVal = 0n): any {
	return {
		type: DataTypes.TEXT,
		get: function (): bigint {
			return BigInt(this.getDataValue(key));
		},
		set: function (val: bigint) {
			return this.setDataValue(key, `${val}`);
		},
		allowNull: false,
		defaultValue: `${defaultVal}`
	};
}