-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
belongs-to.inclusion-resolver.ts
57 lines (51 loc) · 1.66 KB
/
belongs-to.inclusion-resolver.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
// 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 {AnyObject, Options} from '../../common-types';
import {Entity} from '../../model';
import {Filter, Inclusion} from '../../query';
import {EntityCrudRepository} from '../../repositories/repository';
import {
findByForeignKeys,
flattenTargetsOfOneToOneRelation,
StringKeyOf,
uniq,
} from '../relation.helpers';
import {
BelongsToDefinition,
Getter,
InclusionResolver,
} from '../relation.types';
import {resolveBelongsToMetadata} from './belongs-to.helpers';
export function createBelongsToInclusionResolver<
Target extends Entity,
TargetID,
TargetRelations extends object
>(
meta: BelongsToDefinition,
getTargetRepo: Getter<
EntityCrudRepository<Target, TargetID, TargetRelations>
>,
): InclusionResolver {
const relationMeta = resolveBelongsToMetadata(meta);
return async function fetchIncludedModels(
entities: Entity[],
inclusion: Inclusion,
options?: Options,
): Promise<((Target & TargetRelations) | undefined)[]> {
if (!entities.length) return [];
const sourceKey = relationMeta.keyFrom;
const sourceIds = entities.map(e => (e as AnyObject)[sourceKey]);
const targetKey = relationMeta.keyTo as StringKeyOf<Target>;
const targetRepo = await getTargetRepo();
const targetsFound = await findByForeignKeys(
targetRepo,
targetKey,
uniq(sourceIds),
inclusion.scope as Filter<Target>,
options,
);
return flattenTargetsOfOneToOneRelation(sourceIds, targetsFound, targetKey);
};
}