UNPKG

3.11 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.belongsTo = void 0;
8const core_1 = require("@loopback/core");
9const decorators_1 = require("../../decorators");
10const relation_decorator_1 = require("../relation.decorator");
11const relation_types_1 = require("../relation.types");
12/**
13 * Decorator for belongsTo
14 * @param targetResolver - A resolver function that returns the target model for
15 * a belongsTo relation
16 * @param definition - Optional metadata for setting up a belongsTo relation
17 * @param propertyDefinition - Optional metadata for setting up the property
18 * @returns A property decorator
19 */
20function belongsTo(targetResolver, definition, propertyDefinition) {
21 return function (decoratedTarget, decoratedKey) {
22 var _a;
23 const propType = (_a = core_1.MetadataInspector.getDesignTypeForProperty(decoratedTarget, decoratedKey)) !== null && _a !== void 0 ? _a : propertyDefinition === null || propertyDefinition === void 0 ? void 0 : propertyDefinition.type;
24 if (!propType) {
25 const fullPropName = core_1.DecoratorFactory.getTargetName(decoratedTarget, decoratedKey);
26 throw new Error(`Cannot infer type of model property ${fullPropName} because ` +
27 'TypeScript compiler option `emitDecoratorMetadata` is not set. ' +
28 'Please enable `emitDecoratorMetadata` or use the third argument of ' +
29 '`@belongsTo` decorator to specify the property type explicitly.');
30 }
31 const propMeta = Object.assign({},
32 // properties provided by the caller
33 propertyDefinition,
34 // properties enforced by the decorator
35 {
36 type: propType,
37 // TODO(bajtos) Make the foreign key required once our REST API layer
38 // allows controller methods to exclude required properties
39 // required: true,
40 });
41 (0, decorators_1.property)(propMeta)(decoratedTarget, decoratedKey);
42 // @belongsTo() is typically decorating the foreign key property,
43 // e.g. customerId. We need to strip the trailing "Id" suffix from the name.
44 const relationName = decoratedKey.replace(/Id$/, '');
45 const meta = Object.assign(
46 // default values, can be customized by the caller
47 {
48 keyFrom: decoratedKey,
49 name: relationName,
50 },
51 // properties provided by the caller
52 definition,
53 // properties enforced by the decorator
54 {
55 type: relation_types_1.RelationType.belongsTo,
56 targetsMany: false,
57 source: decoratedTarget.constructor,
58 target: targetResolver,
59 });
60 (0, relation_decorator_1.relation)(meta)(decoratedTarget, decoratedKey);
61 };
62}
63exports.belongsTo = belongsTo;
64//# sourceMappingURL=belongs-to.decorator.js.map
\No newline at end of file