Skip to content

Instantly share code, notes, and snippets.

@xwlee
Created December 23, 2018 05:14
Show Gist options
  • Save xwlee/6a6c97b18aa2181fa25a5b86b2b32455 to your computer and use it in GitHub Desktop.
Save xwlee/6a6c97b18aa2181fa25a5b86b2b32455 to your computer and use it in GitHub Desktop.
Apollo Server Upper Case Directive
const {
ApolloServer,
gql,
SchemaDirectiveVisitor
} = require('apollo-server');
const { defaultFieldResolver } = require('graphql');
const typeDefs = gql`
directive @upper on FIELD_DEFINITION
type Query {
hello: String @upper
}
`
const resolvers = {
Query: {
hello: () => 'world'
}
};
class UpperCaseDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
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;
};
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
upper: UpperCaseDirective,
upperCase: UpperCaseDirective
}
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment