/
relations.ts
340 lines (316 loc) · 8.4 KB
/
relations.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import {
Attributes,
CoreModel,
CoreModelDefinition,
FilterAttributes,
ModelAction,
ModelRef,
ModelRefCustom,
ModelRefCustomProperties,
NotEnumerable
} from "./coremodel";
/**
* Raw model without methods
*/
export type RawModel<T extends object> = {
[K in Attributes<T>]?: T[K] extends object ? RawModel<T[K]> : T[K];
};
/**
* Methods of an object
*
* Filter out attributes
*/
export type Methods<T extends object> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
/**
* Model loader with a `get` method
*/
type ModelLoader<T extends CoreModel, K = string> = {
get: () => Promise<T>;
set: (info: K) => void;
toString(): string;
} & Readonly<K>;
/**
* Load related objects
*
* _K is not used but is required to complete the graph
*/
export type ModelRelated<T extends CoreModel, _K extends Attributes<T>> = {
/**
* Query the related objects
* @param query
* @returns
*/
query: (query?: string) => Promise<{ results: T[]; continuationToken?: string }>;
/**
*
* @param model Iterate through all related objects
* @returns
*/
forEach: (model: T) => Promise<void>;
/**
* Get all object linked
* @returns
*/
getAll: () => Promise<T[]>;
};
// Empty class to allow filtering it
export interface ModelLinker {}
/**
* Define a link to 1:n relation
*/
export class ModelLink<T extends CoreModel> implements ModelLinker {
@NotEnumerable
protected parent: CoreModel;
constructor(
protected uuid: string,
protected model: CoreModelDefinition<T>,
parent?: CoreModel
) {
this.parent = parent;
}
async get(): Promise<T> {
return (await this.model.ref(this.uuid).get())?.setContext(this.parent?.getContext());
}
set(id: string | T) {
this.uuid = typeof id === "string" ? id : id.getUuid();
// Set dirty for parent
this.parent?.__dirty.add(
Object.keys(this.parent)
.filter(k => this.parent[k] === this)
.pop()
);
}
toString(): string {
return this.uuid;
}
toJSON(): string {
return this.uuid;
}
getUuid(): string {
return this.uuid;
}
}
/**
* Methods that allow to manage a collection of linked objects
*/
type ModelCollectionManager<T> = {
/**
* Add a linked object
* @param model
* @returns
*/
add: (model: T) => void;
/**
* Remove a linked object
* @param model the model to remove or its uuid
* @returns
*/
remove: (model: T | string) => void;
};
/**
* Link to a collection of objects
*/
export class ModelLinksSimpleArray<T extends CoreModel> extends Array<ModelRef<T>> implements ModelLinker {
@NotEnumerable
private parent: CoreModel;
constructor(
protected model: CoreModelDefinition<T>,
content: any[] = [],
parent?: CoreModel
) {
super();
content.forEach(c => this.add(c));
this.parent = parent;
}
add(model: string | ModelRef<T> | T) {
this.push(
typeof model === "string"
? new ModelRef(model, this.model, this.parent)
: new ModelRef(model.getUuid(), this.model, this.parent)
);
this.parent?.__dirty.add(
Object.keys(this.parent)
.filter(k => this.parent[k] === this)
.pop()
);
}
remove(model: ModelRef<T> | string | T) {
let index = this.findIndex(m => m.toString() === (typeof model === "string" ? model : model.getUuid()));
if (index >= 0) {
this.splice(index, 1);
}
this.parent?.__dirty.add(
Object.keys(this.parent)
.filter(k => this.parent[k] === this)
.pop()
);
}
}
/**
* Link to a collection of objects including some additional data
*/
export class ModelLinksArray<T extends CoreModel, K>
extends Array<ModelRefCustomProperties<T, (K & { uuid: string }) | { getUuid: () => string }>>
implements ModelLinker
{
@NotEnumerable
parent: CoreModel;
constructor(
protected model: CoreModelDefinition<T>,
content: any[] = [],
parent?: CoreModel
) {
super();
this.parent = parent;
this.push(
...content
.filter(c => c && c.uuid)
.map(c => <ModelRefCustomProperties<T, K>>new ModelRefCustom(c.uuid, model, c, this.parent))
);
}
add(
model:
| ModelRefCustomProperties<T, (K & { uuid: string }) | { getUuid: () => string }>
| ((K & { uuid: string }) | { getUuid: () => string })
) {
this.push(
<ModelRefCustomProperties<T, K & ({ uuid: string } | { getUuid: () => string })>>(
(model instanceof ModelRefCustom
? model
: new ModelRefCustom(
(<{ uuid: string }>model).uuid || (<{ getUuid: () => string }>model).getUuid(),
this.model,
model,
this.parent
))
)
);
this.parent?.__dirty.add(
Object.keys(this.parent)
.filter(k => this.parent[k] === this)
.pop()
);
}
remove(model: ModelRefCustomProperties<T, K> | string | T) {
const uuid = typeof model === "string" ? model : (<{ uuid: string }>model).uuid || model.getUuid();
let index = this.findIndex(m => m.getUuid() === uuid);
if (index >= 0) {
this.splice(index, 1);
this.parent?.__dirty.add(
Object.keys(this.parent)
.filter(k => this.parent[k] === this)
.pop()
);
}
}
}
/**
* Define 1:n relation with some sort of additional data or duplicated data
*
* The key of the map is the value of the FK
*/
export type ModelLinksMap<T extends CoreModel, K> = Readonly<{
[key: string]: ModelRefCustomProperties<T, K & ({ uuid: string } | { getUuid: () => string })>;
}> &
ModelCollectionManager<K & ({ uuid: string } | { getUuid: () => string })> &
ModelLinker;
export function createModelLinksMap<T extends CoreModel>(
model: CoreModelDefinition<any>,
data: any = {},
parent?: CoreModel
) {
let result = {
add: (model: ModelRefCustomProperties<T, any>) => {
result[model.uuid || model.getUuid()] = model;
parent?.__dirty.add(
Object.keys(parent)
.filter(k => parent[k] === result)
.pop()
);
},
remove: (model: ModelRefCustomProperties<T, any> | string) => {
// @ts-ignore
const uuid = typeof model === "string" ? model : model.uuid || model.getUuid();
delete result[uuid];
parent?.__dirty.add(
Object.keys(parent)
.filter(k => parent[k] === result)
.pop()
);
}
};
Object.keys(data)
.filter(k => k !== "__proto__")
.forEach(key => {
result[key] = new ModelRefCustom(data[key].uuid, model, data[key], parent);
});
Object.defineProperty(result, "add", { enumerable: false });
Object.defineProperty(result, "remove", { enumerable: false });
return result;
}
/**
* Define the parent of the model
*/
export type ModelParent<T extends CoreModel> = ModelLink<T>;
/**
* Define an export of actions from Model
*/
export type ModelActions = {
[key: string]: ModelAction;
};
/**
* Mapper attribute (target of a Mapper service)
*
* This is not exported as when mapped the target is always an array
* TODO Handle 1:1 map
*/
export class ModelMapLoaderImplementation<T extends CoreModel, K = any> {
@NotEnumerable
protected _model: CoreModelDefinition<T>;
@NotEnumerable
protected _parent: CoreModel;
/**
* The uuid of the object
*/
public uuid: string;
constructor(model: CoreModelDefinition<T>, data: { uuid: string } & K, parent: CoreModel) {
Object.assign(this, data);
this._model = model;
this._parent = parent;
}
/**
*
* @returns the model
*/
async get(): Promise<T> {
return this._model.ref(this.uuid).get(this._parent.getContext());
}
}
/**
* Mapper attribute (target of a Mapper service)
*
* This is not exported as when mapped the target is always an array
* TODO Handle 1:1 map
*/
export type ModelMapLoader<T extends CoreModel, K extends keyof T> = ModelMapLoaderImplementation<T, K> & Pick<T, K>;
/**
* Define a ModelMap attribute
*
* K is used by the compiler to define the field it comes from
*
* This will instructed a ModelMapper to deduplicate information from the T model into this
* current model attribute.
*
* The attribute where the current model uuid is found is defined by K
* The attributes to dedepulicate are defined by the L type
*
* In the T model, the K attribute should be of type ModelLink
*/
export type ModelsMapped<
T extends CoreModel,
// Do not remove used by the compiler
K extends FilterAttributes<T, ModelLinker>,
L extends Attributes<T>
> = Readonly<ModelMapLoader<T, L>[]>;