-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
has-one.inclusion-resolver.ts
52 lines (46 loc) · 1.63 KB
/
has-one.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
// 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,
} from '../relation.helpers';
import {Getter, HasOneDefinition, InclusionResolver} from '../relation.types';
import {resolveHasOneMetadata} from './has-one.helpers';
export function createHasOneInclusionResolver<
Target extends Entity,
TargetID,
TargetRelations extends object
>(
meta: HasOneDefinition,
getTargetRepo: Getter<
EntityCrudRepository<Target, TargetID, TargetRelations>
>,
): InclusionResolver {
const relationMeta = resolveHasOneMetadata(meta);
return async function fetchHasOneModel(
entities: Entity[],
inclusion: Inclusion<Entity>,
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,
sourceIds,
inclusion.scope as Filter<Target>,
options,
);
return flattenTargetsOfOneToOneRelation(sourceIds, targetsFound, targetKey);
};
}