Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
apollo-server-agnostic
Advanced tools
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.
Install with NPM:
npm install apollo-server-agnostic graphql
Install with Yarn:
yarn add apollo-server-agnostic graphql
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
}
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}`);
});
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;
More documentation of ApolloServer can be found in their docs, especially the apollo-server-lambda
docs.
Disabling the GUI requires ApolloServer settings:
const server = new ApolloServer({
introspection: false,
playground: false,
context: context => context,
});
See this Apollo Server issue.
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
}
MIT
FAQs
Framework agnostic Node.js GraphQL Apollo Server
We found that apollo-server-agnostic demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.