0.0.2 • Published 5 years ago

apollo-server-agnostic v0.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

apollo-server-agnostic

Like apollo-server-lambda@2.6.2, but without all the features.

Without all the vendor lock-ins, this Apollo Server implementation can run with any Node.js framework.

Strictly Apollo Server features, such as Apollo Federation and playground options, are available.

Server options, such as CORS and Headers, are left for you to implement with your chosen framework.

Getting Started

Installation

Install with NPM:

npm install apollo-server-agnostic graphql

Install with Yarn:

yarn add apollo-server-agnostic graphql

Setup and Usage

const {
  ApolloServer,
  gql
} = require('apollo-server-agnostic');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: context => context,
});

const graphqlHandler = server.createHandler();

The function graphqlHandler accepts a request object. In order for this module to remain framework agnostic, you must format the request object yourself. It is recommended to encapsulate the object re-mapping code inside a function.

The graphqlHandler function accepts a request object defined as:

// request
type req {
  httpMethod: String, // POST, GET, …
  accept: String, // 'application/json', 'text/html', '*/*', …
  path: String, // /graphql, …
  query: Query, // standardized Query object from request.body or request.queryParams
}

All other parameters passed to the graphqlHandler function will be merged as an array ...ctx and will be passed with the request object as the context for your resolver functions.

Calling graphqlHandler(format(req)) returns a Promise with:

// response
type res {
  body: String // response body, already JSON.stringify()
  headers: Object // response headers
  statusCode: Number // response status code
}

Express

Create a function to format the Express req request object.

// format.js
module.exports.formatExpress = (req) => {
  const httpMethod = req.method;
  const accept = req.headers['Accept'] || req.headers['accept'];
  const path = req.path;
  const query = Object.entries(req.body).length ? req.body : req.query;
  return {
    httpMethod,
    accept,
    path,
    query,
  };
};

Put everything together

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { formatExpress, } = require('./format');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// Create graphqlHandler here

app.get('/graphql', async (req, res) => {
  const response = await graphqlHandler(formatExpress(req));

  res.status(response.statusCode) // use statusCode
    .set(response.headers) // merge headers
    .send(response.body); // send body string
});

app.post('/graphql', async (req, res) => {
  const response = await graphqlHandler(formatExpress(req));

  res.status(response.statusCode) // use statusCode
    .set(response.headers) // merge headers
    .send(response.body); // send body string
});

const listener = app.listen({ port: 3001, }, () => {
  console.log(`🚀 Server ready at http://localhost:${listener.address().port}${server.graphqlPath}`);
});

Claudia API Builder

Create a function to format the Claudia request object.

// format.js
module.exports.formatClaudia = (req) => {
  const httpMethod = req.context.method;
  const accept = req.headers['Accept'] || req.headers['accept'];
  const path = req.proxyRequest.requestContext.path;
  const query = Object.entries(req.body).length ? req.body : req.queryString;
  return {
    httpMethod,
    accept,
    path,
    query,
  };
};

Put everything together

const ApiBuilder = require('claudia-api-builder');
const { formatClaudia, } = require('./format');

const api = new ApiBuilder();

// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
api.corsMaxAge(60);

// Create graphqlHandler here

api.get('/graphql', async request => {
  request.lambdaContext.callbackWaitsForEmptyEventLoop = false;

  const response = await graphqlHandler(formatClaudia(request));

  const body = response.headers['Content-Type'] === 'text/html' ?
    response.body :
    JSON.parse(response.body);

  // You must parse the body so ApiResponse does not JSON.stringify() twice
  return new api.ApiResponse(body, response.headers, response.statusCode);
});

api.post('/graphql', async request => {
  request.lambdaContext.callbackWaitsForEmptyEventLoop = false;

  const response = await graphqlHandler(formatClaudia(request));

  // You must parse the body so ApiResponse does not JSON.stringify() twice
  return new api.ApiResponse(JSON.parse(response.body), response.headers, response.statusCode);
});

module.exports = api;

Notes

More documentation of ApolloServer can be found in their docs, especially the apollo-server-lambda docs.

Disabling the GUI

Disabling the GUI requires ApolloServer settings:

const server = new ApolloServer({
  introspection: false,
  playground: false,
  context: context => context,
});

See this Apollo Server issue.

Passing in Context

Context allows you to pass in additional information with your request, such as authentication headers, etc.

Minimal required to enable context:

const server = new ApolloServer({
  context: context => context,
})

More complex context example:

// inside server setup

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: context => {
    context.db = 'db';
    return context;
  },
});

const graphqlHandler = server.createHandler();

// inside request handler

const response = await graphqlHandler(format(request), { arg1: true, }, 'arg2');

// inside resolver: (parent, args, context, info) => { … }

// context object
{
  db: 'db',
  req: request, // result from format(request)
  ctx: [{ arg1: true, }, 'arg2',], // any other args passed to graphqlHandler
}

License

MIT