UNPKG

graphql2rest

Version:

GraphQL to REST converter: automatically generate a RESTful API from your existing GraphQL API

76 lines (44 loc) 2.24 kB
## Using a remote GraphQL server In this example, we'll use [Apollo Link](https://www.apollographql.com/docs/link/links/http/) to connect via HTTP to a remote GraphQL server. Using Apollo Link with `fetch` is the simplest way to connect GraphQL2REST to an existing GraphQL server, local or remote. Authentication and authorization against the GraphQL server can be taken care of in the *fetch* parameters. #### For example: ```js const path = require('path'); const { schema } = require('./myGraphQLSchema.js'); // a GraphQLSchema object const GraphQL2REST = require('graphql2rest'); const { execute, makePromise } = require('apollo-link'); const { createHttpLink } = require('apollo-link-http'); const fetch = require('node-fetch'); const express = require('express'); const app = express(); const gqlServerUri = 'http://10.20.30.1:3000/api/graphql'; // our existing remote GraphQL server const link = createHttpLink({ uri: gqlServerUri, fetch }); /* GraphQL2REST execute function using apollo-link. Invokes GraphQL operation against gqlServerUri via node-fetch */ const executeGqlLink = (operation) => { return makePromise(execute(link, operation)); }; const GQL_FILES_FOLDER = path.resolve(__dirname,'./gqlFilesFolder'); // folder previously generated by generateGqlQueryFiles() const gql2restOptions = { apiPrefix: '/api', //sets the API base path url manifestFile: path.resolve(__dirname,'./api-manifest.json'), //pathname of manifest file. Default is ./manifest.json gqlGeneratorOutputFolder: GQL_FILES_FOLDER //.gql files folder }; const restRouter = GraphQL2REST.init(schema, executeGqlLink, gql2restOptions); // restRouter now has our REST API attached app.use('/', restRouter); ``` <br> Now the following REST API is mounted and active (based on the [manifest file described earlier](manifest-example.json)): > GET /api/users > GET /api/users/{userId} > POST /api/users > PATCH /api/users/{userId} > DELETE /api/users/{userId} <br> --- Learn more about: - [Filtering and shaping the responses on the client side](Client%20filters.md) - [Customizing and formatting response format](Formatting%20responses.md) <br> [Back to [the tutorial](https://github.com/sisense/graphql2rest#tutorial)]