-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
66 lines (55 loc) · 1.5 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
'use strict';
const AggregateError = require('aggregate-error');
const got = require('got');
const prependHttp = require('prepend-http');
class GraphQLError extends Error {
constructor(err, body) {
super(err.message);
this.name = 'GraphQLError';
this.locations = err.locations;
this.operationName = body.operationName;
this.query = body.query;
this.variables = body.variables;
}
}
const graphqlGot = (url, opts) => {
opts = Object.assign({method: 'POST'}, opts, {json: true});
opts.body = Object.assign({}, {
query: opts.query,
operationName: opts.operationName,
variables: opts.variables
});
delete opts.query;
delete opts.operationName;
delete opts.variables;
if (opts.token) {
opts.headers = Object.assign({}, opts.headers, {
authorization: `bearer ${opts.token}`
});
}
return got(prependHttp(url, {https: true}), opts)
.then(res => {
res.errors = res.body.errors;
res.body = res.body.data;
return res;
})
.catch(err => {
if (err.response && typeof err.response.body === 'object') {
const errors = err.response.body.errors;
const error = Array.isArray(errors) && errors.length > 0 ?
errors.map(x => new GraphQLError(x, opts.body)) :
[new GraphQLError(err, opts.body)];
throw new AggregateError(error);
}
throw err;
});
};
const helpers = [
'get',
'post'
];
for (const x of helpers) {
const method = x.toUpperCase();
graphqlGot[x] = (url, opts) => graphqlGot(url, Object.assign({}, opts, {method}));
}
module.exports = graphqlGot;