1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.createBelongsToAccessor = void 0;
|
8 | const tslib_1 = require("tslib");
|
9 | const debug_1 = tslib_1.__importDefault(require("debug"));
|
10 | const belongs_to_helpers_1 = require("./belongs-to.helpers");
|
11 | const belongs_to_inclusion_resolver_1 = require("./belongs-to.inclusion-resolver");
|
12 | const belongs_to_repository_1 = require("./belongs-to.repository");
|
13 | const debug = (0, debug_1.default)('loopback:repository:relations:belongs-to:accessor');
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | function createBelongsToAccessor(belongsToMetadata, targetRepositoryGetter, sourceRepository) {
|
20 | const meta = (0, belongs_to_helpers_1.resolveBelongsToMetadata)(belongsToMetadata);
|
21 |
|
22 | if (typeof targetRepositoryGetter === 'function') {
|
23 | targetRepositoryGetter = {
|
24 | [meta.target().name]: targetRepositoryGetter,
|
25 | };
|
26 | }
|
27 | debug('Resolved BelongsTo relation metadata: %o', meta);
|
28 | const result = async function getTargetInstanceOfBelongsTo(sourceId, polymorphicTypes) {
|
29 | if (meta.polymorphic !== false) {
|
30 | if (!polymorphicTypes || polymorphicTypes.length === 0) {
|
31 | console.warn('It is highly recommended to specify the polymorphicTypes param when using polymorphic types.');
|
32 | }
|
33 | }
|
34 | const foreignKey = meta.keyFrom;
|
35 | const primaryKey = meta.keyTo;
|
36 | const sourceModel = await sourceRepository.findById(sourceId);
|
37 | const foreignKeyValue = sourceModel[foreignKey];
|
38 |
|
39 |
|
40 |
|
41 | if (!foreignKeyValue) {
|
42 | return undefined;
|
43 | }
|
44 |
|
45 | const constraint = { [primaryKey]: foreignKeyValue };
|
46 | const constrainedRepo = new belongs_to_repository_1.DefaultBelongsToRepository(targetRepositoryGetter, constraint, belongsToMetadata.target);
|
47 | return constrainedRepo.get({ polymorphicType: polymorphicTypes });
|
48 | };
|
49 | result.inclusionResolver = (0, belongs_to_inclusion_resolver_1.createBelongsToInclusionResolver)(meta, targetRepositoryGetter);
|
50 | return result;
|
51 | }
|
52 | exports.createBelongsToAccessor = createBelongsToAccessor;
|
53 |
|
\ | No newline at end of file |