Serverless GraphQL handler with Vercel

Execute GraphQL queries and mutations inside a serverless function hosted by Vercel.

Notes

1import { makeExecutableSchema } from "@graphql-tools/schema";
2import { graphql, GraphQLError } from "graphql";
3
4const typeDefs = `
5 type Query {
6 users: [User]
7 }
8
9 type User {
10 username: String!
11 avatar: String!
12 }
13`;
14
15const resolvers = {
16 Query: {
17 users: () => [
18 {
19 username: "notrab",
20 },
21 {
22 username: "rauchg",
23 },
24 ],
25 },
26 User: {
27 avatar: (root) => `https://github.com/${root.username}.png`,
28 },
29};
30
31const schema = makeExecutableSchema({ typeDefs, resolvers });
32
1export default async (req, res) => {
2 const { method, body, query: qs } = req;
3
4 if (method !== "GET" && method !== "POST") {
5 return res
6 .status(405)
7 .setHeader("Allow", "GET,POST")
8 .send("Method not allowed");
9 }
10
11 if (!qs.query && method === "GET")
12 return res.status(400).json({
13 statusCode: 400,
14 error: "Bad Request",
15 message: "GET query missing",
16 });
17
18 const { query, variables, operationName } = method === "GET" ? qs : body;
19
20 try {
21 const result = await graphql(
22 schema,
23 query,
24 null,
25 null,
26 variables,
27 operationName
28 );
29
30 res.status(200).json(result);
31 } catch (err) {
32 res.status(400).json(new GraphQLError(err.message));
33 }
34};
35