-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
graphql.ts
67 lines (60 loc) · 1.75 KB
/
graphql.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* SPDX-FileCopyrightText: 2016-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */
import type { Request } from "express";
import { graphqlHTTP } from "express-graphql";
import fs from "fs";
import {
formatError,
GraphQLObjectType,
GraphQLSchema,
printSchema,
} from "graphql";
import { noop } from "lodash";
import path from "path";
import { reportError } from "../core";
import env from "../env";
import { Context } from "./context";
import * as mutations from "./mutations";
import * as queries from "./queries";
import { nodeField, nodesField } from "./types/node";
import { ValidationError } from "./utils";
/**
* GraphQL API schema.
*/
export const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "Root",
description: "The top-level API",
fields: {
node: nodeField,
nodes: nodesField,
...queries,
},
}),
mutation: new GraphQLObjectType({
name: "Mutation",
fields: mutations,
}),
});
/**
* GraphQL middleware for Express.js
*/
export const graphql = graphqlHTTP((req, res, params) => ({
schema,
context: new Context(req as Request),
graphiql: env.APP_ENV !== "prod",
pretty: !env.isProduction,
customFormatErrorFn: (err) => {
if (err.originalError instanceof ValidationError) {
return { ...formatError(err), errors: err.originalError.errors };
}
reportError(err.originalError || err, req as Request, params);
console.error(err.originalError || err);
return formatError(err);
},
}));
export function updateSchema(cb: fs.NoParamCallback = noop): void {
const file = path.resolve(__dirname, "../schema.graphql");
const output = printSchema(schema, { commentDescriptions: true });
fs.writeFile(file, output, { encoding: "utf-8" }, cb);
}