Skip to content

Latest commit

 

History

History
76 lines (44 loc) · 2.19 KB

Using remote GraphQL server.md

File metadata and controls

76 lines (44 loc) · 2.19 KB

Using a remote GraphQL server

In this example, we'll use Apollo Link 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:

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);

Now the following REST API is mounted and active (based on the manifest file described earlier):

GET /api/users

GET /api/users/{userId}

POST /api/users

PATCH /api/users/{userId}

DELETE /api/users/{userId}



Learn more about:


[Back to the tutorial]