-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
model.ts
247 lines (203 loc) · 8.29 KB
/
model.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { EMPTY_OBJECT } from '@sequelize/utils';
import { cloneDataType } from '../../abstract-dialect/data-types-utils.js';
import { BaseError } from '../../errors/base-error.js';
import { mergeModelOptions } from '../../model-definition.js';
import { initModel } from '../../model-typescript.js';
import type { AttributeOptions, ModelAttributes, ModelOptions, ModelStatic } from '../../model.js';
import type { Sequelize } from '../../sequelize.js';
import { isModelStatic } from '../../utils/model-utils.js';
import { cloneDeep, getAllOwnEntries } from '../../utils/object.js';
export interface RegisteredModelOptions extends ModelOptions {
/**
* Abstract models cannot be used directly, or registered.
* They exist only to be extended by other models.
*/
abstract?: boolean;
}
export interface RegisteredAttributeOptions {
[key: string]: Partial<AttributeOptions>;
}
interface RegisteredOptions {
model: RegisteredModelOptions;
attributes: RegisteredAttributeOptions;
}
const registeredOptions = new WeakMap<ModelStatic, RegisteredOptions>();
/**
* Registers model options for future registering of the Model using Model.init
* Subsequent calls for the same model & attributeName will be merged, with the newer call taking precedence.
* 'sequelize' option is not accepted here. Pass it through `Model.init` when registering the model.
*
* @param model
* @param options
*/
export function registerModelOptions(model: ModelStatic, options: RegisteredModelOptions): void {
if (!registeredOptions.has(model)) {
registeredOptions.set(model, { model: options, attributes: {} });
return;
}
// merge-able: scopes, indexes
const existingModelOptions = registeredOptions.get(model)!.model;
try {
mergeModelOptions(existingModelOptions, options, false);
} catch (error) {
throw new BaseError(
`Multiple decorators are trying to register conflicting options on model ${model.name}`,
{ cause: error },
);
}
}
/**
* Registers attribute options for future registering of the Model using Model.init
* Subsequent calls for the same model & attributeName will be merged, with the newer call taking precedence.
*
* @param model
* @param attributeName
* @param options
*/
export function registerModelAttributeOptions(
model: ModelStatic,
attributeName: string,
options: Partial<AttributeOptions>,
): void {
if (!registeredOptions.has(model)) {
registeredOptions.set(model, {
model: {},
attributes: {
[attributeName]: options,
},
});
return;
}
const existingAttributesOptions = registeredOptions.get(model)!.attributes;
if (!(attributeName in existingAttributesOptions)) {
existingAttributesOptions[attributeName] = options;
return;
}
const existingOptions = existingAttributesOptions[attributeName];
mergeAttributeOptions(attributeName, model, existingOptions, options, false);
}
export function mergeAttributeOptions(
attributeName: string,
model: ModelStatic,
existingOptions: Partial<AttributeOptions>,
options: Partial<AttributeOptions>,
overrideOnConflict: boolean,
): Partial<AttributeOptions> {
for (const [optionName, optionValue] of Object.entries(options) as Array<
[keyof AttributeOptions, any]
>) {
if (existingOptions[optionName] === undefined) {
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error -- This error only occurs on TS 5.3+
// @ts-ignore -- this function is very fuzzy in terms of typing due to how generic it is.
existingOptions[optionName] = optionValue;
continue;
}
// These are objects. We merge their properties, unless the same key is used in both values.
if (optionName === 'validate') {
for (const [subOptionName, subOptionValue] of getAllOwnEntries(optionValue)) {
if (subOptionName in existingOptions[optionName]! && !overrideOnConflict) {
throw new Error(
`Multiple decorators are attempting to register option ${optionName}[${JSON.stringify(subOptionName)}] of attribute ${attributeName} on model ${model.name}.`,
);
}
// @ts-expect-error -- runtime type checking is enforced by model
existingOptions[optionName][subOptionName] = subOptionValue;
}
continue;
}
if (optionName === 'index' || optionName === 'unique') {
if (!existingOptions[optionName]) {
existingOptions[optionName] = [];
} else if (!Array.isArray(existingOptions[optionName])) {
// @ts-expect-error -- runtime type checking is enforced by model
existingOptions[optionName] = [existingOptions[optionName]];
}
if (Array.isArray(optionValue)) {
// @ts-expect-error -- runtime type checking is enforced by model
existingOptions[optionName] = [...existingOptions[optionName], ...optionValue];
} else {
existingOptions[optionName] = [...existingOptions[optionName], optionValue];
}
continue;
}
if (optionValue === existingOptions[optionName] || overrideOnConflict) {
continue;
}
throw new Error(
`Multiple decorators are attempting to set different values for the option ${optionName} of attribute ${attributeName} on model ${model.name}.`,
);
}
return existingOptions;
}
export function initDecoratedModel(model: ModelStatic, sequelize: Sequelize): boolean {
const isAbstract = registeredOptions.get(model)?.model.abstract;
if (isAbstract) {
return false;
}
const modelOptions = getRegisteredModelOptions(model);
const attributeOptions = getRegisteredAttributeOptions(model);
initModel(model, attributeOptions as ModelAttributes, {
...modelOptions,
sequelize,
});
return true;
}
const NON_INHERITABLE_MODEL_OPTIONS = ['modelName', 'name', 'tableName'] as const;
function getRegisteredModelOptions(model: ModelStatic): ModelOptions {
const modelOptions = registeredOptions.get(model)?.model ?? (EMPTY_OBJECT as ModelOptions);
const parentModel = Object.getPrototypeOf(model);
if (isModelStatic(parentModel)) {
const parentModelOptions: ModelOptions = { ...getRegisteredModelOptions(parentModel) };
for (const nonInheritableOption of NON_INHERITABLE_MODEL_OPTIONS) {
delete parentModelOptions[nonInheritableOption];
}
// options that must be cloned
parentModelOptions.indexes = cloneDeep(parentModelOptions.indexes);
parentModelOptions.defaultScope = cloneDeep(parentModelOptions.defaultScope);
parentModelOptions.scopes = cloneDeep(parentModelOptions.scopes);
parentModelOptions.validate = cloneDeep(parentModelOptions.validate);
parentModelOptions.hooks = cloneDeep(parentModelOptions.hooks);
return mergeModelOptions(parentModelOptions, modelOptions, true);
}
return modelOptions;
}
function getRegisteredAttributeOptions(model: ModelStatic): RegisteredAttributeOptions {
const descendantAttributes = {
...(registeredOptions.get(model)?.attributes ?? (EMPTY_OBJECT as RegisteredAttributeOptions)),
};
const parentModel = Object.getPrototypeOf(model);
if (isModelStatic(parentModel)) {
const parentAttributes: RegisteredAttributeOptions = getRegisteredAttributeOptions(parentModel);
for (const attributeName of Object.keys(parentAttributes)) {
const descendantAttribute = descendantAttributes[attributeName];
const parentAttribute = { ...parentAttributes[attributeName] };
if (parentAttribute.type) {
if (typeof parentAttribute.type === 'function') {
parentAttribute.type = new parentAttribute.type();
} else {
parentAttribute.type = cloneDataType(parentAttribute.type);
}
}
// options that must be cloned
parentAttribute.unique = cloneDeep(parentAttribute.unique);
parentAttribute.index = cloneDeep(parentAttribute.index);
parentAttribute.references = cloneDeep(parentAttribute.references);
parentAttribute.validate = cloneDeep(parentAttribute.validate);
if (!descendantAttribute) {
descendantAttributes[attributeName] = parentAttribute;
} else {
descendantAttributes[attributeName] = mergeAttributeOptions(
attributeName,
model,
parentAttribute,
descendantAttribute,
true,
);
}
}
}
return descendantAttributes;
}
export function isDecoratedModel(model: ModelStatic): boolean {
return registeredOptions.has(model);
}