-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (81 loc) · 2.89 KB
/
index.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const fs = require('fs');
module.exports = (Grown, util) => {
function _startGraphQLServer(typeDefs, resolvers) {
const gql = require('graphql');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const _schema = makeExecutableSchema({ typeDefs, resolvers });
return ctx => {
const body = ctx.req.body || {};
const query = ctx.req.query || {};
const _query = body.query || query.body;
const data = body.variables || query.data || {};
ctx.res.setHeader('Content-Type', 'application/json');
/* istanbul ignore else */
if (!_query) {
ctx.res.write('{"errors":["Missing input body or query"]}');
ctx.res.status(422).end();
return;
}
return gql.graphql(_schema, _query, null, ctx, data)
.then(result => {
let statusCode = 200;
/* istanbul ignore else */
if (result.errors && result.errors.length > 0) {
statusCode = ctx.res.statusCode > 200 && ctx.res.statusCode < 500 ? ctx.res.statusCode : 400;
result.errors.forEach(e => {
e.message = e.message.replace(/^\d+ [_A-Z]+: /, '');
e.description = e.stack.toString();
});
}
ctx.res.write(JSON.stringify(result));
ctx.res.status(statusCode).end();
});
};
}
function _bindGraphQLServer(schemas, container) {
/* istanbul ignore else */
if (!(schemas && Array.isArray(schemas))) {
throw new Error('Missing or invalid schemas');
}
const typeDefs = schemas.map(file => {
try {
return fs.readFileSync(file, 'utf8');
} catch (e) {
throw new Error(`Unable to load schema, given '${file}'`);
}
});
/* istanbul ignore else */
if (!(container && container.registry)) {
throw new Error('Missing or invalid container');
}
const resolvers = {};
container.forEach(target => {
['Mutation', 'Query'].forEach(method => {
Object.keys(target[method] || {}).forEach(prop => {
/* istanbul ignore else */
if (typeof target[method][prop] !== 'function') {
throw new Error(`Expecting ${prop} to be a function, given '${target[method][prop]}'`);
}
resolvers[method] = resolvers[method] || {};
resolvers[method][prop] = function $call(root, args, { req }) {
return Promise.resolve()
.then(() => target[method][prop]({ root, args, req }))
.catch(error => {
error = util.cleanError(error, Grown.cwd);
throw error;
});
};
});
});
});
return this._startGraphQLServer(typeDefs, resolvers);
}
return Grown('GraphQL', {
_startGraphQLServer,
_bindGraphQLServer,
setup(schemas, container) {
return this._bindGraphQLServer(schemas, container);
},
});
};