UNPKG

2.35 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/repository
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {PropertyDecoratorFactory} from '@loopback/core';
7import {buildModelDefinition} from '../decorators';
8import {Model, RelationDefinitionMap} from '../model';
9import {RelationType} from './relation.types';
10
11export const RELATIONS_KEY = 'loopback:relations';
12
13/**
14 * Decorator for relations
15 * @param definition
16 * @returns A property decorator
17 */
18export function relation(definition?: Object) {
19 // Apply relation definition to the model class
20 return PropertyDecoratorFactory.createDecorator(RELATIONS_KEY, definition, {
21 decoratorName: '@relation',
22 });
23}
24
25/**
26 * Get metadata of all relations defined on a given model class.
27 *
28 * @param modelCtor - The model class (the constructor function).
29 * @returns A map of relation definitions
30 */
31export function getModelRelations(
32 modelCtor: typeof Model,
33): RelationDefinitionMap {
34 // Build model definitions if `@model` is missing
35 const modelDef = buildModelDefinition(modelCtor);
36 return modelDef?.relations || {};
37}
38
39//
40// placeholder decorators for relations that are not implemented yet
41// TODO: move these decorators to per-relation subdirectories
42//
43
44/**
45 * Decorator for embedsOne
46 * @param definition
47 * @returns A property decorator
48 */
49export function embedsOne(definition?: Object) {
50 const rel = Object.assign({type: RelationType.embedsOne}, definition);
51 return PropertyDecoratorFactory.createDecorator(RELATIONS_KEY, rel, {
52 decoratorName: '@embedsOne',
53 });
54}
55
56/**
57 * Decorator for embedsMany
58 * @param definition
59 * @returns A property decorator
60 */
61export function embedsMany(definition?: Object) {
62 const rel = Object.assign({type: RelationType.embedsMany}, definition);
63 return PropertyDecoratorFactory.createDecorator(RELATIONS_KEY, rel, {
64 decoratorName: '@embedsMany',
65 });
66}
67
68/**
69 * Decorator for referencesOne
70 * @param definition
71 * @returns A property decorator
72 */
73export function referencesOne(definition?: Object) {
74 const rel = Object.assign({type: RelationType.referencesOne}, definition);
75 return PropertyDecoratorFactory.createDecorator(RELATIONS_KEY, rel, {
76 decoratorName: '@referencesOne',
77 });
78}