forked from matthewmueller/express-graph.ql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (53 loc) · 1.23 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
/**
* Module Dependencies
*/
var body = require('body-parser')
/**
* Export `middleware`
*/
module.exports = middleware
/**
* Setup middleware
*
* @param {Schema|Function} schema_or_fn
* @return {Function}
*/
function middleware (schema_or_fn) {
return function (req, res, next) {
var schema = schema_or_fn.name !== 'query'
? schema_or_fn(req, res, next)
: schema_or_fn
if (req.method === 'GET') {
return next(new Error('express-graph.ql does not support GET requests yet'))
}
// parse the request body if we haven't already
if (!req.body) body.json()(req, res, run)
else run()
// run the query against our schema
function run () {
schema(req.body.query, variables(req.body.variables))
.then(function (data) {
if (data.errors) {
return res.send({
errors: data.errors.map(function (error) {
return error.stack
})
})
} else {
res.send(data)
}
})
}
}
}
/**
* Coerce variables
*
* @param {Mixed} vars
* @return {Object}
*/
function variables (vars) {
if (!vars) return {}
if (typeof vars === 'string') return JSON.parse(vars)
return vars
}