@nestjs/graphql
Version:
Nest - modern, fast, powerful node.js web framework (@graphql)
43 lines (42 loc) • 1.44 kB
JavaScript
import { parse } from 'graphql';
import { DirectiveParsingError } from '../schema-builder/errors/directive-parsing.error.js';
import { LazyMetadataStorage } from '../schema-builder/storages/lazy-metadata.storage.js';
import { TypeMetadataStorage } from '../schema-builder/storages/type-metadata.storage.js';
/**
* Adds one or more directives to a field, type, or handler. Passing an array
* attaches every directive in a single decorator call, equivalent to stacking
* multiple `@Directive(...)` decorators.
*
* @publicApi
*/
export function Directive(sdl) {
const sdls = Array.isArray(sdl) ? sdl : [sdl];
sdls.forEach(validateDirective);
return (target, key) => {
LazyMetadataStorage.store(() => {
sdls.forEach((singleSdl) => {
if (key) {
TypeMetadataStorage.addDirectivePropertyMetadata({
target: target.constructor,
fieldName: key,
sdl: singleSdl,
});
}
else {
TypeMetadataStorage.addDirectiveMetadata({
target: target,
sdl: singleSdl,
});
}
});
});
};
}
function validateDirective(sdl) {
try {
parse(`type String ${sdl}`);
}
catch (err) {
throw new DirectiveParsingError(sdl);
}
}