@nestjs/graphql
Version:
Nest - modern, fast, powerful node.js web framework (@graphql)
48 lines (47 loc) • 2.21 kB
JavaScript
import { isFunction } from '@nestjs/common/utils/shared.utils.js';
import { inheritPropertyInitializers, inheritTransformationMetadata, inheritValidationMetadata, } from '@nestjs/mapped-types';
import { Field } from '../decorators/index.js';
import { MetadataLoader } from '../plugin/metadata-loader.js';
import { getFieldsAndDecoratorForType } from '../schema-builder/utils/get-fields-and-decorator.util.js';
import { applyFieldDecorators } from './type-helpers.utils.js';
export function PickType(classRef, keys, decorator) {
const { fields, decoratorFactory } = getFieldsAndDecoratorForType(classRef);
const isInheritedPredicate = (propertyKey) => keys.includes(propertyKey);
class PickObjectType {
constructor() {
inheritPropertyInitializers(this, classRef, isInheritedPredicate);
}
}
if (decorator && decorator !== decoratorFactory) {
decoratorFactory({ isAbstract: true })(PickObjectType);
decorator({ isAbstract: true })(PickObjectType);
}
else {
decoratorFactory({ isAbstract: true })(PickObjectType);
}
inheritValidationMetadata(classRef, PickObjectType, isInheritedPredicate);
inheritTransformationMetadata(classRef, PickObjectType, isInheritedPredicate);
function applyFields(fields) {
fields
.filter((item) => keys.includes(item.name))
.forEach((item) => {
if (isFunction(item.typeFn)) {
// Execute type function eagerly to update the type options object (before "clone" operation)
// when the passed function (e.g., @Field(() => Type)) lazily returns an array.
item.typeFn();
}
Field(item.typeFn, { ...item.options })(PickObjectType.prototype, item.name);
applyFieldDecorators(PickObjectType, item);
});
}
applyFields(fields);
// Register a refresh hook to update the fields when the serialized metadata
// is loaded from file.
MetadataLoader.addRefreshHook(() => {
const { fields } = getFieldsAndDecoratorForType(classRef, {
overrideFields: true,
});
applyFields(fields);
});
return PickObjectType;
}