UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2018,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.createHasOneRepositoryFactory = void 0;
8const tslib_1 = require("tslib");
9const debug_1 = tslib_1.__importDefault(require("debug"));
10const has_one_helpers_1 = require("./has-one.helpers");
11const has_one_inclusion_resolver_1 = require("./has-one.inclusion-resolver");
12const has_one_repository_1 = require("./has-one.repository");
13const debug = (0, debug_1.default)('loopback:repository:relations:has-one:repository-factory');
14/**
15 * Enforces a constraint on a repository based on a relationship contract
16 * between models. For example, if a Customer model is related to an Address model
17 * via a HasOne relation, then, the relational repository returned by the
18 * factory function would be constrained by a Customer model instance's id(s).
19 *
20 * If the target model is polymorphic, i.e. stored within different repositories,
21 * supply the targetRepositoryGetter with a dictionary in the form of {[typeName: string]: repositoryGetter}
22 *
23 * @param relationMetadata - The relation metadata used to describe the
24 * relationship and determine how to apply the constraint.
25 * @param targetRepositoryGetter - The repository or a dictionary of classname - repository,
26 * which represents the target model of a relation attached to a datasource.
27 * For the dictionary, the key is the class name of the concrete class the the polymorphic model.
28 * @returns The factory function which accepts a foreign key value to constrain
29 * the given target repository
30 */
31function createHasOneRepositoryFactory(relationMetadata, targetRepositoryGetter) {
32 const meta = (0, has_one_helpers_1.resolveHasOneMetadata)(relationMetadata);
33 // resolve the repositoryGetter into a dictionary
34 if (typeof targetRepositoryGetter === 'function') {
35 targetRepositoryGetter = {
36 [meta.target().name]: targetRepositoryGetter,
37 };
38 }
39 debug('Resolved HasOne relation metadata: %o', meta);
40 const result = function (fkValue) {
41 // eslint-disable-next-line @typescript-eslint/no-explicit-any
42 const constraint = { [meta.keyTo]: fkValue };
43 return new has_one_repository_1.DefaultHasOneRepository(targetRepositoryGetter, constraint, relationMetadata.target);
44 };
45 result.inclusionResolver = (0, has_one_inclusion_resolver_1.createHasOneInclusionResolver)(meta, targetRepositoryGetter);
46 return result;
47}
48exports.createHasOneRepositoryFactory = createHasOneRepositoryFactory;
49//# sourceMappingURL=has-one.repository-factory.js.map
\No newline at end of file