-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathhas-many-through.helpers.ts
387 lines (362 loc) · 10.4 KB
/
has-many-through.helpers.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright IBM Corp. and LoopBack contributors 2020. All Rights Reserved.
// Node module: @loopback/repository
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import debugFactory from 'debug';
import {camelCase} from 'lodash';
import {
DataObject,
deduplicate,
Entity,
HasManyDefinition,
InvalidRelationError,
isTypeResolver,
} from '../..';
import {resolveHasManyMetaHelper} from './has-many.helpers';
const debug = debugFactory(
'loopback:repository:relations:has-many-through:helpers',
);
export type HasManyThroughResolvedDefinition = HasManyDefinition & {
keyTo: string;
keyFrom: string;
through: {
keyTo: string;
keyFrom: string;
polymorphic: false | {discriminator: string};
};
};
/**
* Creates target constraint based on through models
* @param relationMeta - resolved hasManyThrough metadata
* @param throughInstances - an array of through instances
*
* @example
* ```ts
* const resolvedMetadata = {
* // .. other props
* keyFrom: 'id',
* keyTo: 'id',
* through: {
* model: () => CategoryProductLink,
* keyFrom: 'categoryId',
* keyTo: 'productId',
* },
* };
* createTargetConstraintFromThrough(resolvedMetadata,[{
id: 2,
categoryId: 2,
productId: 8,
}]);
* >>> {id: 8}
* createTargetConstraintFromThrough(resolvedMetadata, [
{
id: 2,
categoryId: 2,
productId: 8,
}, {
id: 1,
categoryId: 2,
productId: 9,
}
]);
>>> {id: {inq: [9, 8]}}
* ```
*/
export function createTargetConstraintFromThrough<
Target extends Entity,
Through extends Entity,
>(
relationMeta: HasManyThroughResolvedDefinition,
throughInstances: Through[],
): DataObject<Target> {
const fkValues = getTargetKeysFromThroughModels(
relationMeta,
throughInstances,
);
const targetPrimaryKey = relationMeta.keyTo;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const constraint: any = {
[targetPrimaryKey]: fkValues.length === 1 ? fkValues[0] : {inq: fkValues},
};
return constraint;
}
/**
* Returns an array of target fks of the given throughInstances.
*
* @param relationMeta - resolved hasManyThrough metadata
* @param throughInstances - an array of through instances
*
* @example
* ```ts
* const resolvedMetadata = {
* // .. other props
* keyFrom: 'id',
* keyTo: 'id',
* through: {
* model: () => CategoryProductLink,
* keyFrom: 'categoryId',
* keyTo: 'productId',
* },
* };
* getTargetKeysFromThroughModels(resolvedMetadata,[{
id: 2,
categoryId: 2,
productId: 8,
}]);
* >>> [8]
* getTargetKeysFromThroughModels(resolvedMetadata, [
{
id: 2,
categoryId: 2,
productId: 8,
}, {
id: 1,
categoryId: 2,
productId: 9,
}
]);
>>> [8, 9]
*/
export function getTargetKeysFromThroughModels<
Through extends Entity,
TargetID,
>(
relationMeta: HasManyThroughResolvedDefinition,
throughInstances: Through[],
): TargetID[] {
const targetFkName = relationMeta.through.keyTo;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let fkValues: any = throughInstances.map(
(throughInstance: Through) =>
throughInstance[targetFkName as keyof Through],
);
fkValues = deduplicate(fkValues);
return fkValues as TargetID[];
}
/**
* Creates through constraint based on the source key
*
* @param relationMeta - resolved hasManyThrough metadata
* @param fkValue - foreign key of the source instance
* @internal
*
* @example
* ```ts
* const resolvedMetadata = {
* // .. other props
* keyFrom: 'id',
* keyTo: 'id',
* through: {
* model: () => CategoryProductLink,
* keyFrom: 'categoryId',
* keyTo: 'productId',
* },
* };
* createThroughConstraintFromSource(resolvedMetadata, 1);
*
* >>> {categoryId: 1}
* ```
*/
export function createThroughConstraintFromSource<
Through extends Entity,
SourceID,
>(
relationMeta: HasManyThroughResolvedDefinition,
fkValue: SourceID,
): DataObject<Through> {
const sourceFkName = relationMeta.through.keyFrom;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const constraint: any = {[sourceFkName]: fkValue};
return constraint;
}
/**
* Returns an array of target ids of the given target instances.
*
* @param relationMeta - resolved hasManyThrough metadata
* @param targetInstances - an array of target instances
*
* @example
* ```ts
* const resolvedMetadata = {
* // .. other props
* keyFrom: 'id',
* keyTo: 'id',
* through: {
* model: () => CategoryProductLink,
* keyFrom: 'categoryId',
* keyTo: 'productId',
* },
* };
* getTargetKeysFromTargetModels(resolvedMetadata,[{
id: 2,
des: 'a target',
}]);
* >>> [2]
* getTargetKeysFromTargetModels(resolvedMetadata, [
{
id: 2,
des: 'a target',
}, {
id: 1,
des: 'a target',
}
]);
>>> [2, 1]
*/
export function getTargetIdsFromTargetModels<Target extends Entity, TargetID>(
relationMeta: HasManyThroughResolvedDefinition,
targetInstances: Target[],
): TargetID[] {
const targetId = relationMeta.keyTo;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let ids = [] as any;
ids = targetInstances.map(
(targetInstance: Target) => targetInstance[targetId as keyof Target],
);
ids = deduplicate(ids);
return ids as TargetID[];
}
/**
* Creates through constraint based on the target foreign key
*
* @param relationMeta - resolved hasManyThrough metadata
* @param fkValue an array of the target instance foreign keys
* @internal
*
* @example
* ```ts
* const resolvedMetadata = {
* // .. other props
* keyFrom: 'id',
* keyTo: 'id',
* through: {
* model: () => CategoryProductLink,
* keyFrom: 'categoryId',
* keyTo: 'productId',
* },
* };
* createThroughConstraintFromTarget(resolvedMetadata, [3]);
*
* >>> {productId: 3}
*
* createThroughConstraintFromTarget(resolvedMetadata, [3,4]);
*
* >>> {productId: {inq:[3,4]}}
*/
export function createThroughConstraintFromTarget<
Through extends Entity,
TargetID,
>(
relationMeta: HasManyThroughResolvedDefinition,
fkValues: TargetID[],
): DataObject<Through> {
if (fkValues === undefined || fkValues.length === 0) {
throw new Error('"fkValue" must be provided');
}
const targetFkName = relationMeta.through.keyTo;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const constraint: any =
fkValues.length === 1
? {[targetFkName]: fkValues[0]}
: {[targetFkName]: {inq: fkValues}};
return constraint as DataObject<Through>;
}
/**
* Resolves given hasMany metadata if target is specified to be a resolver.
* Mainly used to infer what the `keyTo` property should be from the target's
* belongsTo metadata
* @param relationMeta - hasManyThrough metadata to resolve
* @internal
*/
export function resolveHasManyThroughMetadata(
relationMeta: HasManyDefinition,
): HasManyThroughResolvedDefinition {
// some checks and relationMeta.keyFrom are handled in here
relationMeta = resolveHasManyMetaHelper(relationMeta);
if (!relationMeta.through) {
const reason = 'through must be specified';
throw new InvalidRelationError(reason, relationMeta);
}
if (!isTypeResolver(relationMeta.through?.model)) {
const reason = 'through.model must be a type resolver';
throw new InvalidRelationError(reason, relationMeta);
}
const throughModel = relationMeta.through.model();
const throughModelProperties = throughModel.definition?.properties;
const targetModel = relationMeta.target();
const targetModelProperties = targetModel.definition?.properties;
// check if metadata is already complete
if (
relationMeta.through.keyTo &&
throughModelProperties[relationMeta.through.keyTo] &&
relationMeta.through.keyFrom &&
throughModelProperties[relationMeta.through.keyFrom] &&
relationMeta.keyTo &&
targetModelProperties[relationMeta.keyTo] &&
(relationMeta.through.polymorphic === false ||
(typeof relationMeta.through.polymorphic === 'object' &&
relationMeta.through.polymorphic.discriminator.length > 0))
) {
// The explicit cast is needed because of a limitation of type inference
return relationMeta as HasManyThroughResolvedDefinition;
}
const sourceModel = relationMeta.source;
debug(
'Resolved model %s from given metadata: %o',
targetModel.modelName,
targetModel,
);
debug(
'Resolved model %s from given metadata: %o',
throughModel.modelName,
throughModel,
);
const sourceFkName =
relationMeta.through.keyFrom ?? camelCase(sourceModel.modelName + '_id');
if (!throughModelProperties[sourceFkName]) {
const reason = `through model ${throughModel.name} is missing definition of source foreign key`;
throw new InvalidRelationError(reason, relationMeta);
}
const targetFkName =
relationMeta.through.keyTo ?? camelCase(targetModel.modelName + '_id');
if (!throughModelProperties[targetFkName]) {
const reason = `through model ${throughModel.name} is missing definition of target foreign key`;
throw new InvalidRelationError(reason, relationMeta);
}
const targetPrimaryKey =
relationMeta.keyTo ?? targetModel.definition.idProperties()[0];
if (!targetPrimaryKey || !targetModelProperties[targetPrimaryKey]) {
const reason = `target model ${targetModel.modelName} does not have any primary key (id property)`;
throw new InvalidRelationError(reason, relationMeta);
}
let throughPolymorphic: false | {discriminator: string};
if (
relationMeta.through.polymorphic === undefined ||
relationMeta.through.polymorphic === false ||
!relationMeta.through.polymorphic
) {
const polymorphicFalse = false as const;
throughPolymorphic = polymorphicFalse;
} else {
if (relationMeta.through.polymorphic === true) {
const polymorphicObject: {discriminator: string} = {
discriminator: camelCase(relationMeta.target().name + '_type'),
};
throughPolymorphic = polymorphicObject;
} else {
const polymorphicObject: {discriminator: string} = relationMeta.through
.polymorphic as {discriminator: string};
throughPolymorphic = polymorphicObject;
}
}
return Object.assign(relationMeta, {
keyTo: targetPrimaryKey,
keyFrom: relationMeta.keyFrom!,
through: {
...relationMeta.through,
keyTo: targetFkName,
keyFrom: sourceFkName,
polymorphic: throughPolymorphic,
},
});
}