Created
July 15, 2022 10:09
-
-
Save koolamusic/cd96ab96eb70462151fae6a8f3821798 to your computer and use it in GitHub Desktop.
GraphQL directives to work with Nestjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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