Skip to content

Instantly share code, notes, and snippets.

@xwlee
Created December 23, 2018 06:01
Show Gist options
  • Save xwlee/faa11fe5fa5cde06e47e59b1583cafee to your computer and use it in GitHub Desktop.
Save xwlee/faa11fe5fa5cde06e47e59b1583cafee to your computer and use it in GitHub Desktop.
Apollo Server REST Directive
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