UNPKG

2.44 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.PickType = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5const mapped_types_1 = require("@nestjs/mapped-types");
6const decorators_1 = require("../decorators");
7const metadata_loader_1 = require("../plugin/metadata-loader");
8const get_fields_and_decorator_util_1 = require("../schema-builder/utils/get-fields-and-decorator.util");
9const type_helpers_utils_1 = require("./type-helpers.utils");
10function PickType(classRef, keys, decorator) {
11 const { fields, decoratorFactory } = (0, get_fields_and_decorator_util_1.getFieldsAndDecoratorForType)(classRef);
12 const isInheritedPredicate = (propertyKey) => keys.includes(propertyKey);
13 class PickObjectType {
14 constructor() {
15 (0, mapped_types_1.inheritPropertyInitializers)(this, classRef, isInheritedPredicate);
16 }
17 }
18 decoratorFactory({ isAbstract: true })(PickObjectType);
19 if (decorator) {
20 decorator({ isAbstract: true })(PickObjectType);
21 }
22 else {
23 decoratorFactory({ isAbstract: true })(PickObjectType);
24 }
25 (0, mapped_types_1.inheritValidationMetadata)(classRef, PickObjectType, isInheritedPredicate);
26 (0, mapped_types_1.inheritTransformationMetadata)(classRef, PickObjectType, isInheritedPredicate);
27 function applyFields(fields) {
28 fields
29 .filter((item) => keys.includes(item.name))
30 .forEach((item) => {
31 if ((0, shared_utils_1.isFunction)(item.typeFn)) {
32 // Execute type function eagerly to update the type options object (before "clone" operation)
33 // when the passed function (e.g., @Field(() => Type)) lazily returns an array.
34 item.typeFn();
35 }
36 (0, decorators_1.Field)(item.typeFn, { ...item.options })(PickObjectType.prototype, item.name);
37 (0, type_helpers_utils_1.applyFieldDecorators)(PickObjectType, item);
38 });
39 }
40 applyFields(fields);
41 // Register a refresh hook to update the fields when the serialized metadata
42 // is loaded from file.
43 metadata_loader_1.MetadataLoader.addRefreshHook(() => {
44 const { fields } = (0, get_fields_and_decorator_util_1.getFieldsAndDecoratorForType)(classRef, {
45 overrideFields: true,
46 });
47 applyFields(fields);
48 });
49 return PickObjectType;
50}
51exports.PickType = PickType;