UNPKG

type-graphql-utils

Version:

utilities to transform type-graphql types

71 lines (70 loc) 3.19 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Required = exports.Partial = exports.Omit = exports.Pick = exports.buildType = exports.buildEnum = void 0; const type_graphql_1 = require("type-graphql"); const metadata = (0, type_graphql_1.getMetadataStorage)(); function buildEnum(Class, name) { const enumObj = {}; metadata.fields.forEach((f) => { if (f.target !== Class && !f.target.isPrototypeOf(Class)) return; enumObj[f.name] = f.name; }); (0, type_graphql_1.registerEnumType)(enumObj, { name }); return enumObj; } exports.buildEnum = buildEnum; function buildType(BaseClass, buildFn, options) { let ChildClass = class ChildClass { }; ChildClass = __decorate([ (0, type_graphql_1.InputType)({ isAbstract: true }), (0, type_graphql_1.ObjectType)({ isAbstract: true }) ], ChildClass); metadata.fields.forEach((f) => { if (f.target !== BaseClass && !f.target.isPrototypeOf(BaseClass)) return; f.getType(); // detect array type options, issue #3 const field = buildFn(f); if (field instanceof Array) { field.forEach((field) => metadata.fields.push({ ...field, target: ChildClass })); } else if (field) { metadata.fields.push({ ...field, target: ChildClass }); } }); if (options?.directives) { const fieldNames = metadata.fields.filter((f) => f.target === ChildClass).map((f) => f.name); metadata.fieldDirectives.forEach((f) => { if (f.target !== BaseClass && !f.target.isPrototypeOf(BaseClass)) return; if (fieldNames.includes(f.fieldName)) { metadata.fieldDirectives.push({ ...f, target: ChildClass }); } }); } return ChildClass; } exports.buildType = buildType; function Pick(BaseClass, names, options) { return buildType(BaseClass, (f) => f.name in names ? f : undefined, options); } exports.Pick = Pick; function Omit(BaseClass, names, options) { return buildType(BaseClass, (f) => f.name in names ? undefined : f, options); } exports.Omit = Omit; function Partial(BaseClass, names, options) { return buildType(BaseClass, (f) => !names || f.name in names ? { ...f, typeOptions: { ...f.typeOptions, nullable: true } } : f, options); } exports.Partial = Partial; function Required(BaseClass, names, options) { return buildType(BaseClass, (f) => !names || f.name in names ? { ...f, typeOptions: { ...f.typeOptions, nullable: false } } : f, options); } exports.Required = Required;