-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
relation.helpers.ts
187 lines (161 loc) · 5.17 KB
/
relation.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
// Copyright IBM Corp. 2019. 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 * as assert from 'assert';
import {AnyObject} from 'loopback-datasource-juggler';
import {Options} from '../common-types';
import {Entity} from '../model';
import {Filter, Where} from '../query';
import {EntityCrudRepository, getRepositoryCapabilities} from '../repositories';
// TODO(bajtos) add test coverage
/**
* Dedupe an array
* @param {Array} input an array
* @returns {Array} an array with unique items
*/
export function uniq<T>(input: T[]): T[] {
const uniqArray: T[] = [];
if (!input) {
return uniqArray;
}
assert(Array.isArray(input), 'array argument is required');
const comparableA = input.map(item =>
isBsonType(item) ? item.toString() : item,
);
for (let i = 0, n = comparableA.length; i < n; i++) {
if (comparableA.indexOf(comparableA[i]) === i) {
uniqArray.push(input[i]);
}
}
return uniqArray;
}
// TODO(bajtos) add test coverage
export function isBsonType(value: unknown): value is object {
if (typeof value !== 'object' || !value) return false;
// [email protected] stores _bsontype on ObjectID instance, [email protected] on prototype
return check(value) || check(value.constructor.prototype);
function check(target: unknown) {
return Object.prototype.hasOwnProperty.call(target, '_bsontype');
}
}
// TODO(bajtos) add test coverage
export async function findByForeignKeys<
Target extends Entity,
TargetID,
TargetRelations extends object,
ForeignKey
>(
targetRepository: EntityCrudRepository<Target, TargetID, TargetRelations>,
fkName: StringKeyOf<Target>,
fkValues: ForeignKey[],
_scope?: Filter<Target>,
options?: Options,
): Promise<(Target & TargetRelations)[]> {
const repoCapabilities = getRepositoryCapabilities(targetRepository);
const pageSize = repoCapabilities.inqLimit || 256;
// TODO(bajtos) add test coverage
const queries = splitByPageSize(fkValues, pageSize).map(fks => {
const where = ({
[fkName]: fks.length === 1 ? fks[0] : {inq: fks},
} as unknown) as Where<Target>;
// TODO(bajtos) take into account scope fields like pagination, fields, etc
// FIXME(bajtos) for v1, reject unsupported scope options
const targetFilter = {where};
return targetFilter;
});
const results = await Promise.all(
queries.map(q => targetRepository.find(q, options)),
);
return flatten(results);
}
function flatten<T>(items: T[][]): T[] {
// Node.js 11+
if (typeof items.flat === 'function') {
return items.flat(1);
}
// Node.js 8 and 10
return ([] as T[]).concat(...items);
}
function splitByPageSize<T>(items: T[], pageSize: number): T[][] {
if (pageSize < 0) return [items];
if (!pageSize) throw new Error(`Invalid page size: ${pageSize}`);
const pages: T[][] = [];
for (let i = 0; i < items.length; i += pageSize) {
pages.push(items.slice(i, i + pageSize));
}
return pages;
}
export type StringKeyOf<T> = Extract<keyof T, string>;
// TODO(bajtos) add test coverage
export function buildLookupMap<Key, InType, OutType = InType>(
list: InType[],
keyName: StringKeyOf<InType>,
reducer: (accumulator: OutType | undefined, current: InType) => OutType,
): Map<Key, OutType> {
const lookup = new Map<Key, OutType>();
for (const entity of list) {
const key = getKeyValue(entity, keyName) as Key;
const original = lookup.get(key);
const reduced = reducer(original, entity);
lookup.set(key, reduced);
}
return lookup;
}
// TODO(bajtos) add test coverage
export function flattenTargetsOfOneToOneRelation<
SourceWithRelations extends Entity,
Target extends Entity
>(
sourceIds: unknown[],
targetEntities: Target[],
targetKey: StringKeyOf<Target>,
): (Target | undefined)[] {
const lookup = buildLookupMap<unknown, Target, Target>(
targetEntities,
targetKey,
reduceAsSingleItem,
);
return flattenMapByKeys(sourceIds, lookup);
}
export function reduceAsSingleItem<T>(_acc: T | undefined, it: T) {
return it;
}
// TODO(bajtos) add test coverage
export function flattenTargetsOfOneToManyRelation<Target extends Entity>(
sourceIds: unknown[],
targetEntities: Target[],
targetKey: StringKeyOf<Target>,
): (Target[] | undefined)[] {
const lookup = buildLookupMap<unknown, Target, Target[]>(
targetEntities,
targetKey,
reduceAsArray,
);
return flattenMapByKeys(sourceIds, lookup);
}
export function reduceAsArray<T>(acc: T[] | undefined, it: T) {
if (acc) acc.push(it);
else acc = [it];
return acc;
}
export function getKeyValue<T>(model: T, keyName: string) {
const rawKey = (model as AnyObject)[keyName];
// Hacky workaround for MongoDB, see _SPIKE_.md for details
if (typeof rawKey === 'object' && rawKey.constructor.name === 'ObjectID') {
return rawKey.toString();
}
return rawKey;
}
export function flattenMapByKeys<T>(
sourceIds: unknown[],
targetMap: Map<unknown, T>,
): (T | undefined)[] {
const result: (T | undefined)[] = new Array(sourceIds.length);
for (const ix in sourceIds) {
const key = sourceIds[ix];
const target = targetMap.get(key);
result[ix] = target;
}
return result;
}