UNPKG

@nestjs/graphql

Version:

GraphQL for NestJS: code-first and schema-first APIs, resolvers as providers, subscriptions, federation and generated SDL, on Apollo or Mercurius.

66 lines (65 loc) • 3.01 kB
import { SetMetadata } from '@nestjs/common'; import { isFunction, isObject, isString, } from '@nestjs/common/utils/shared.utils.js'; import { FIELD_RESOLVER_MIDDLEWARE_METADATA, RESOLVER_NAME_METADATA, RESOLVER_PROPERTY_METADATA, } from '../graphql.constants.js'; import { LazyMetadataStorage } from '../schema-builder/storages/lazy-metadata.storage.js'; import { TypeMetadataStorage } from '../schema-builder/storages/type-metadata.storage.js'; import { reflectTypeFromMetadata } from '../utils/reflection.utilts.js'; /** * Property resolver (method) Decorator. * * @publicApi */ export function ResolveField(propertyNameOrFunc, typeFuncOrOptions, resolveFieldOptions) { return (target, key, descriptor) => { // Every parameter is optional and may be passed as "undefined" (e.g. // `@ResolveField('name', undefined, options)`), so the arguments are told // apart by their type rather than by their position. const args = [propertyNameOrFunc, typeFuncOrOptions, resolveFieldOptions]; const typeFunc = args.find((arg) => isFunction(arg)); let options = args.find((arg) => isObject(arg)); const propertyName = isString(propertyNameOrFunc) ? propertyNameOrFunc : options?.name; SetMetadata(RESOLVER_NAME_METADATA, propertyName)(target, key, descriptor); SetMetadata(RESOLVER_PROPERTY_METADATA, true)(target, key, descriptor); SetMetadata(FIELD_RESOLVER_MIDDLEWARE_METADATA, options?.middleware)(target, key, descriptor); options = isObject(options) ? { name: propertyName, ...options, } : propertyName ? { name: propertyName } : {}; LazyMetadataStorage.store(target.constructor, () => { let typeOptions, typeFn; try { const implicitTypeMetadata = reflectTypeFromMetadata({ metadataKey: 'design:returntype', prototype: target, propertyKey: key, explicitTypeFn: typeFunc, typeOptions: options, }); typeOptions = implicitTypeMetadata.options; typeFn = implicitTypeMetadata.typeFn; } catch { // No type to reflect: the field must be declared on the model, which // the options (e.g. "nullable") still apply to. typeOptions = { ...options }; } TypeMetadataStorage.addResolverPropertyMetadata({ kind: 'external', methodName: key, schemaName: options.name || key, target: target.constructor, typeFn, typeOptions, description: options.description, deprecationReason: options.deprecationReason, complexity: options.complexity, }); }); }; }