1 | ;
|
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
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.defineModelClass = void 0;
|
8 | const tslib_1 = require("tslib");
|
9 | const assert = tslib_1.__importStar(require("assert"));
|
10 | const decorators_1 = require("./decorators");
|
11 | /**
|
12 | * Create (define) a new model class with the given name and definition.
|
13 | *
|
14 | * @remarks
|
15 | *
|
16 | * ```ts
|
17 | * const Product = defineModelClass(Entity, new ModelDefinition('Product'));
|
18 | * ```
|
19 | *
|
20 | * To enable type safety, you should describe properties of your model:
|
21 | *
|
22 | * ```ts
|
23 | * const Product = defineModelClass<
|
24 | * typeof Entity,
|
25 | * {id: number, name: string}
|
26 | * >(Entity, new ModelDefinition('Product'));
|
27 | * ```
|
28 | *
|
29 | * If your model allows arbitrary (free-form) properties, then add `AnyObject`
|
30 | * to the type describing model properties.
|
31 | *
|
32 | * ```ts
|
33 | * const Product = defineModelClass<
|
34 | * typeof Entity,
|
35 | * AnyObject & {id: number},
|
36 | * >(Entity, new ModelDefinition('Product'));
|
37 | * ```
|
38 | *
|
39 | * @param base The base model to extend, typically Model or Entity.
|
40 | * You can also use your own base class, e.g. `User`.
|
41 | * @param definition Definition of the model to create.
|
42 | * @typeParam BaseCtor Constructor type of the base class,
|
43 | * e.g `typeof Model` or `typeof Entity`
|
44 | * @typeParam Props Interface describing model properties,
|
45 | * e.g. `{title: string}` or `AnyObject & {id: number}`.
|
46 | */
|
47 | function defineModelClass(base /* Model or Entity */, definition) {
|
48 | const modelName = definition.name;
|
49 | const defineNamedModelClass = new Function(base.name, `return class ${modelName} extends ${base.name} {}`);
|
50 | const modelClass = defineNamedModelClass(base);
|
51 | assert.equal(modelClass.name, modelName);
|
52 | // Apply `@model(definition)` to the generated class
|
53 | (0, decorators_1.model)(definition)(modelClass);
|
54 | return modelClass;
|
55 | }
|
56 | exports.defineModelClass = defineModelClass;
|
57 | //# sourceMappingURL=define-model-class.js.map |
\ | No newline at end of file |