UNPKG

2.35 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2019,2020. All Rights Reserved.
3// Node module: @loopback/repository
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.createHasManyInclusionResolver = void 0;
8const tslib_1 = require("tslib");
9const debug_1 = tslib_1.__importDefault(require("debug"));
10const relation_helpers_1 = require("../relation.helpers");
11const has_many_helpers_1 = require("./has-many.helpers");
12const debug = (0, debug_1.default)('loopback:repository:relations:has-many:inclusion-resolver');
13/**
14 * Creates InclusionResolver for HasMany relation.
15 * Notice that this function only generates the inclusionResolver.
16 * It doesn't register it for the source repository.
17 *
18 * Notice: scope field for inclusion is not supported yet.
19 *
20 * @param meta - resolved metadata of the hasMany relation
21 * @param getTargetRepo - target repository i.e where related instances are
22 */
23function createHasManyInclusionResolver(meta, getTargetRepo) {
24 const relationMeta = (0, has_many_helpers_1.resolveHasManyMetadata)(meta);
25 return async function fetchHasManyModels(entities, inclusion, options) {
26 if (!entities.length)
27 return [];
28 debug('Fetching target models for entities:', entities);
29 debug('Relation metadata:', relationMeta);
30 const sourceKey = relationMeta.keyFrom;
31 const sourceIds = entities.map(e => e[sourceKey]);
32 const targetKey = relationMeta.keyTo;
33 debug('Parameters:', { sourceKey, sourceIds, targetKey });
34 debug('sourceId types', sourceIds.map(i => typeof i));
35 const scope = typeof inclusion === 'string' ? {} : inclusion.scope;
36 const targetRepo = await getTargetRepo();
37 const targetsFound = await (0, relation_helpers_1.findByForeignKeys)(targetRepo, targetKey, sourceIds, scope, options);
38 debug('Targets found:', targetsFound);
39 const result = (0, relation_helpers_1.flattenTargetsOfOneToManyRelation)(sourceIds, targetsFound, targetKey);
40 debug('fetchHasManyModels result', result);
41 return result;
42 };
43}
44exports.createHasManyInclusionResolver = createHasManyInclusionResolver;
45//# sourceMappingURL=has-many.inclusion-resolver.js.map
\No newline at end of file