graphql-directive-rest
Introduction
GraphQL is often used to integrate applications with REST API. Using this directive allows you to make REST integrations without creating any resolvers 🎉 😮
Table of Contents
Installation
yarn add graphql-directive-rest
This package requires graphql and graphql-tools as peer dependency
Usage
@rest
directive
Standard approach, without the const makeExecutableSchema = ;const restDirective = ;const fetch = ; const typeDefs = ` type User { login: String avatar_url: String } type Me { gender: String email: String admin: String } type Query { me(gender: String): Me users: [User] user(user: String): User }`; const resolvers = Query: Me: ; moduleexports = ; `; const resolvers module.exports = makeExecutableSchema({ typeDefs, schemaDirectives: { rest: restDirective, },});
@rest
directive
Using When using @rest
directive, we don't need to write any resolvers 🎉
const makeExecutableSchema = ;const restDirective = ; const GITHUB_URL = 'https://api.github.com';const USER_URL = 'https://randomuser.me/api';const ADMIN_URL = 'https://yesno.wtf/api'; const typeDefs = ` type User { login: String avatar_url: String } type Me { gender: String email: String admin: String @rest(url: "" extractFromResponse: "answer") } type Query { me(gender: String): Me @rest(url: "/?gender=$gender" extractFromResponse: "results[0]") users: [User] @rest(url: "/users") user(user: String): User @rest(url: "/users/$user") }`; moduleexports = ;
Warning! Directive overwrites your resolvers if they're defined
Example queries:
query { users { login avatar_url }}
query($user: String) { user(user: $user) { login avatar_url }}
query($gender: String) { me(gender: $gender) { gender email admin }}
Directive Parameters
Directive params:
url
: String required
Endpoint from where we want to get the data.
extractFromResponse
: String
The path where is the data that we want to get.
Response:
Examples of usage extractFromResponse
To get the title: "results[0].name.title"
or to get the gender: "results[0].gender"
Contributing
I would love to see your contribution. ❤️
For local development (and testing), all you have to do is to run yarn
and then yarn dev
. This will start the Apollo server and you are ready to contribute 🎉
Run yarn test (try --watch
flag) for unit tests (we are using Jest)
LICENSE
The MIT License (MIT) 2018 - Luke Czyszczonik - mailto:lukasz.czyszczonik@gmail.com