UNPKG

2.72 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var apollo_server_core_1 = require("apollo-server-core");
4var gql_1 = require("./gql");
5function graphqlLodashExpress(options) {
6 if (!options) {
7 throw new Error('Apollo Server requires options.');
8 }
9 if (arguments.length > 1) {
10 throw new Error("Apollo Server expects exactly one argument, got " + arguments.length);
11 }
12 return function (req, res, next) {
13 var originalQuery = req.method === 'POST' ? req.body : req.query;
14 var transform, apply, isBatch = false;
15 if (Array.isArray(originalQuery)) {
16 isBatch = true;
17 var res_1 = originalQuery.map(function (q) { return gql_1.graphqlLodash(q.query, q.operationName); });
18 transform = res_1.map(function (t) { return t.transform; });
19 apply = res_1.map(function (t) { return t.apply; });
20 }
21 else {
22 var res_2 = gql_1.graphqlLodash(originalQuery.query, originalQuery.operationName);
23 transform = res_2.transform;
24 apply = res_2.apply;
25 }
26 apollo_server_core_1.runHttpQuery([req, res], {
27 method: req.method,
28 options: options,
29 query: originalQuery,
30 })
31 .then(function (gqlResponse) {
32 if (isBatch) {
33 var result = JSON.parse(gqlResponse);
34 return JSON.stringify(result.map(function (r, i) {
35 if (apply[i]) {
36 return transform[i](r);
37 }
38 else {
39 return r;
40 }
41 }));
42 }
43 else {
44 if (apply) {
45 return JSON.stringify({
46 data: transform(JSON.parse(gqlResponse).data),
47 });
48 }
49 else {
50 return gqlResponse;
51 }
52 }
53 })
54 .then(function (gqlResponse) {
55 res.setHeader('Content-Type', 'application/json');
56 res.write(gqlResponse);
57 res.end();
58 }, function (error) {
59 if ('HttpQueryError' !== error.name) {
60 return next(error);
61 }
62 if (error.headers) {
63 Object.keys(error.headers).forEach(function (header) {
64 res.setHeader(header, error.headers[header]);
65 });
66 }
67 res.statusCode = error.statusCode;
68 res.write(error.message);
69 res.end();
70 });
71 };
72}
73exports.graphqlLodashExpress = graphqlLodashExpress;
74//# sourceMappingURL=express.js.map
\No newline at end of file