Created
December 23, 2018 05:14
-
-
Save xwlee/6a6c97b18aa2181fa25a5b86b2b32455 to your computer and use it in GitHub Desktop.
Apollo Server Upper Case Directive
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
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