Created
December 23, 2018 06:01
-
-
Save xwlee/faa11fe5fa5cde06e47e59b1583cafee to your computer and use it in GitHub Desktop.
Apollo Server REST 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 fetch = require('node-fetch'); | |
const typeDefs = gql` | |
directive @rest(url: String) on FIELD_DEFINITION | |
type Query { | |
users: [User] @rest(url: "https://jsonplaceholder.typicode.com/users") | |
} | |
type User { | |
id: Int | |
name: String | |
username: String | |
email: String | |
} | |
`; | |
class RestDirective extends SchemaDirectiveVisitor { | |
visitFieldDefinition(field) { | |
const { url } = this.args; | |
field.resolve = () => { | |
const res = fetch(url) | |
.then(resp => resp.json()) | |
return res; | |
}; | |
} | |
} | |
const server = new ApolloServer({ | |
typeDefs, | |
schemaDirectives: { | |
rest: RestDirective | |
} | |
}); | |
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