Skip to content

Instantly share code, notes, and snippets.

@koolamusic
Created July 15, 2022 10:09
Show Gist options
  • Save koolamusic/cd96ab96eb70462151fae6a8f3821798 to your computer and use it in GitHub Desktop.
Save koolamusic/cd96ab96eb70462151fae6a8f3821798 to your computer and use it in GitHub Desktop.
GraphQL directives to work with Nestjs
import { SchemaDirectiveVisitor } from '@graphql-tools/utils';
import { defaultFieldResolver, GraphQLField, GraphQLString } from 'graphql';
import formatDate from 'dateformat';
export class DateFormatDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;
const { defaultFormat } = this.args;
field.args.push({
deprecationReason: undefined,
astNode: undefined,
defaultValue: undefined,
description: undefined,
extensions: undefined,
name: 'format',
type: GraphQLString,
});
field.resolve = async (source, { format, ...otherArgs }, context, info) => {
const date = await resolve.call(this, source, otherArgs, context, info);
return formatDate(date, format || defaultFormat);
};
field.type = GraphQLString;
}
}
import { SchemaDirectiveVisitor } from '@graphql-tools/utils';
import { defaultFieldResolver, GraphQLField } from 'graphql';
export class UpperCaseDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (...args) {
const result = await resolve.apply(this, args);
if (typeof result === 'string') {
return result.toUpperCase();
}
return result;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment