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');
const typeDefs = gql`
type Query {
hello: String
}
`;
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:
type req {
httpMethod: String,
accept: String,
path: String,
query: Query,
}
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:
type res {
body: String
headers: Object
statusCode: Number
}
Express
Code Samples
Create a function to format the Express req
request object.
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());
app.get('/graphql', async (req, res) => {
const response = await graphqlHandler(formatExpress(req));
res.status(response.statusCode)
.set(response.headers)
.send(response.body);
});
app.post('/graphql', async (req, res) => {
const response = await graphqlHandler(formatExpress(req));
res.status(response.statusCode)
.set(response.headers)
.send(response.body);
});
const listener = app.listen({ port: 3001, }, () => {
console.log(`🚀 Server ready at http://localhost:${listener.address().port}${server.graphqlPath}`);
});
Claudia API Builder
Code Samples
Create a function to format the Claudia request
object.
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();
api.corsMaxAge(60);
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);
return new api.ApiResponse(body, response.headers, response.statusCode);
});
api.post('/graphql', async request => {
request.lambdaContext.callbackWaitsForEmptyEventLoop = false;
const response = await graphqlHandler(formatClaudia(request));
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:
const server = new ApolloServer({
typeDefs,
resolvers,
context: context => {
context.db = 'db';
return context;
},
});
const graphqlHandler = server.createHandler();
const response = await graphqlHandler(format(request), { arg1: true, }, 'arg2');
{
db: 'db',
req: request,
ctx: [{ arg1: true, }, 'arg2',],
}
License
MIT