1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.graphqlHTTP = graphqlHTTP;
|
7 | exports.getGraphQLParams = getGraphQLParams;
|
8 |
|
9 | var _accepts = _interopRequireDefault(require("accepts"));
|
10 |
|
11 | var _httpErrors = _interopRequireDefault(require("http-errors"));
|
12 |
|
13 | var _graphql = require("graphql");
|
14 |
|
15 | var _parseBody = require("./parseBody");
|
16 |
|
17 | var _renderGraphiQL = require("./renderGraphiQL");
|
18 |
|
19 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | function graphqlHTTP(options) {
|
26 | if (!options) {
|
27 | throw new Error('GraphQL middleware requires options.');
|
28 | }
|
29 |
|
30 | return async function graphqlMiddleware(request, response) {
|
31 |
|
32 | let params;
|
33 | let showGraphiQL = false;
|
34 | let graphiqlOptions;
|
35 | let formatErrorFn = _graphql.formatError;
|
36 | let pretty = false;
|
37 | let result;
|
38 |
|
39 | try {
|
40 |
|
41 | try {
|
42 | params = await getGraphQLParams(request);
|
43 | } catch (error) {
|
44 |
|
45 |
|
46 | const optionsData = await resolveOptions();
|
47 | pretty = optionsData.pretty ?? false;
|
48 | formatErrorFn = optionsData.customFormatErrorFn ?? optionsData.formatError ?? formatErrorFn;
|
49 | throw error;
|
50 | }
|
51 |
|
52 |
|
53 | const optionsData = await resolveOptions(params);
|
54 |
|
55 | const schema = optionsData.schema;
|
56 | const rootValue = optionsData.rootValue;
|
57 | const validationRules = optionsData.validationRules ?? [];
|
58 | const fieldResolver = optionsData.fieldResolver;
|
59 | const typeResolver = optionsData.typeResolver;
|
60 | const graphiql = optionsData.graphiql ?? false;
|
61 | const extensionsFn = optionsData.extensions;
|
62 | const context = optionsData.context ?? request;
|
63 | const parseFn = optionsData.customParseFn ?? _graphql.parse;
|
64 | const executeFn = optionsData.customExecuteFn ?? _graphql.execute;
|
65 | const validateFn = optionsData.customValidateFn ?? _graphql.validate;
|
66 | pretty = optionsData.pretty ?? false;
|
67 | formatErrorFn = optionsData.customFormatErrorFn ?? optionsData.formatError ?? formatErrorFn;
|
68 |
|
69 | if (schema == null) {
|
70 | throw (0, _httpErrors.default)(500, 'GraphQL middleware options must contain a schema.');
|
71 | }
|
72 |
|
73 |
|
74 | if (request.method !== 'GET' && request.method !== 'POST') {
|
75 | throw (0, _httpErrors.default)(405, 'GraphQL only supports GET and POST requests.', {
|
76 | headers: {
|
77 | Allow: 'GET, POST'
|
78 | }
|
79 | });
|
80 | }
|
81 |
|
82 |
|
83 | const {
|
84 | query,
|
85 | variables,
|
86 | operationName
|
87 | } = params;
|
88 | showGraphiQL = canDisplayGraphiQL(request, params) && graphiql !== false;
|
89 |
|
90 | if (typeof graphiql !== 'boolean') {
|
91 | graphiqlOptions = graphiql;
|
92 | }
|
93 |
|
94 |
|
95 |
|
96 | if (query == null) {
|
97 | if (showGraphiQL) {
|
98 | return respondWithGraphiQL(response, graphiqlOptions);
|
99 | }
|
100 |
|
101 | throw (0, _httpErrors.default)(400, 'Must provide query string.');
|
102 | }
|
103 |
|
104 |
|
105 | const schemaValidationErrors = (0, _graphql.validateSchema)(schema);
|
106 |
|
107 | if (schemaValidationErrors.length > 0) {
|
108 |
|
109 | throw (0, _httpErrors.default)(500, 'GraphQL schema validation error.', {
|
110 | graphqlErrors: schemaValidationErrors
|
111 | });
|
112 | }
|
113 |
|
114 |
|
115 | let documentAST;
|
116 |
|
117 | try {
|
118 | documentAST = parseFn(new _graphql.Source(query, 'GraphQL request'));
|
119 | } catch (syntaxError) {
|
120 |
|
121 | throw (0, _httpErrors.default)(400, 'GraphQL syntax error.', {
|
122 | graphqlErrors: [syntaxError]
|
123 | });
|
124 | }
|
125 |
|
126 |
|
127 | const validationErrors = validateFn(schema, documentAST, [..._graphql.specifiedRules, ...validationRules]);
|
128 |
|
129 | if (validationErrors.length > 0) {
|
130 |
|
131 | throw (0, _httpErrors.default)(400, 'GraphQL validation error.', {
|
132 | graphqlErrors: validationErrors
|
133 | });
|
134 | }
|
135 |
|
136 |
|
137 | if (request.method === 'GET') {
|
138 |
|
139 | const operationAST = (0, _graphql.getOperationAST)(documentAST, operationName);
|
140 |
|
141 | if (operationAST && operationAST.operation !== 'query') {
|
142 |
|
143 |
|
144 |
|
145 | if (showGraphiQL) {
|
146 | return respondWithGraphiQL(response, graphiqlOptions, params);
|
147 | }
|
148 |
|
149 |
|
150 | throw (0, _httpErrors.default)(405, `Can only perform a ${operationAST.operation} operation from a POST request.`, {
|
151 | headers: {
|
152 | Allow: 'POST'
|
153 | }
|
154 | });
|
155 | }
|
156 | }
|
157 |
|
158 |
|
159 | try {
|
160 | result = await executeFn({
|
161 | schema,
|
162 | document: documentAST,
|
163 | rootValue,
|
164 | contextValue: context,
|
165 | variableValues: variables,
|
166 | operationName,
|
167 | fieldResolver,
|
168 | typeResolver
|
169 | });
|
170 | } catch (contextError) {
|
171 |
|
172 | throw (0, _httpErrors.default)(400, 'GraphQL execution context error.', {
|
173 | graphqlErrors: [contextError]
|
174 | });
|
175 | }
|
176 |
|
177 |
|
178 |
|
179 | if (extensionsFn) {
|
180 | const extensions = await extensionsFn({
|
181 | document: documentAST,
|
182 | variables,
|
183 | operationName,
|
184 | result,
|
185 | context
|
186 | });
|
187 |
|
188 | if (extensions != null) {
|
189 | result = { ...result,
|
190 | extensions
|
191 | };
|
192 | }
|
193 | }
|
194 | } catch (error) {
|
195 |
|
196 | response.statusCode = error.status ?? 500;
|
197 |
|
198 | if (error.headers != null) {
|
199 | for (const [key, value] of Object.entries(error.headers)) {
|
200 | response.setHeader(key, value);
|
201 | }
|
202 | }
|
203 |
|
204 | result = {
|
205 | data: undefined,
|
206 | errors: error.graphqlErrors ?? [error]
|
207 | };
|
208 | }
|
209 |
|
210 |
|
211 |
|
212 |
|
213 |
|
214 |
|
215 | if (response.statusCode === 200 && result.data == null) {
|
216 | response.statusCode = 500;
|
217 | }
|
218 |
|
219 |
|
220 | if (result.errors) {
|
221 | result.errors = result.errors.map(formatErrorFn);
|
222 | }
|
223 |
|
224 |
|
225 | if (showGraphiQL) {
|
226 | return respondWithGraphiQL(response, graphiqlOptions, params, result);
|
227 | }
|
228 |
|
229 |
|
230 |
|
231 |
|
232 | if (!pretty && typeof response.json === 'function') {
|
233 | response.json(result);
|
234 | } else {
|
235 | const payload = JSON.stringify(result, null, pretty ? 2 : 0);
|
236 | sendResponse(response, 'application/json', payload);
|
237 | }
|
238 |
|
239 | async function resolveOptions(requestParams) {
|
240 | const optionsResult = await Promise.resolve(typeof options === 'function' ? options(request, response, requestParams) : options);
|
241 |
|
242 | if (optionsResult == null || typeof optionsResult !== 'object') {
|
243 | throw new Error('GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.');
|
244 | }
|
245 |
|
246 | if (optionsResult.formatError) {
|
247 |
|
248 | console.warn('`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.');
|
249 | }
|
250 |
|
251 | return optionsResult;
|
252 | }
|
253 | };
|
254 | }
|
255 |
|
256 | function respondWithGraphiQL(response, options, params, result) {
|
257 | const data = {
|
258 | query: params?.query,
|
259 | variables: params?.variables,
|
260 | operationName: params?.operationName,
|
261 | result
|
262 | };
|
263 | const payload = (0, _renderGraphiQL.renderGraphiQL)(data, options);
|
264 | return sendResponse(response, 'text/html', payload);
|
265 | }
|
266 |
|
267 |
|
268 |
|
269 |
|
270 |
|
271 | async function getGraphQLParams(request) {
|
272 | const urlData = new URLSearchParams(request.url.split('?')[1]);
|
273 | const bodyData = await (0, _parseBody.parseBody)(request);
|
274 |
|
275 | let query = urlData.get('query') ?? bodyData.query;
|
276 |
|
277 | if (typeof query !== 'string') {
|
278 | query = null;
|
279 | }
|
280 |
|
281 |
|
282 | let variables = urlData.get('variables') ?? bodyData.variables;
|
283 |
|
284 | if (typeof variables === 'string') {
|
285 | try {
|
286 | variables = JSON.parse(variables);
|
287 | } catch (error) {
|
288 | throw (0, _httpErrors.default)(400, 'Variables are invalid JSON.');
|
289 | }
|
290 | } else if (typeof variables !== 'object') {
|
291 | variables = null;
|
292 | }
|
293 |
|
294 |
|
295 | let operationName = urlData.get('operationName') || bodyData.operationName;
|
296 |
|
297 | if (typeof operationName !== 'string') {
|
298 | operationName = null;
|
299 | }
|
300 |
|
301 | const raw = urlData.get('raw') != null || bodyData.raw !== undefined;
|
302 | return {
|
303 | query,
|
304 | variables,
|
305 | operationName,
|
306 | raw
|
307 | };
|
308 | }
|
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 | function canDisplayGraphiQL(request, params) {
|
315 |
|
316 |
|
317 | return !params.raw && (0, _accepts.default)(request).types(['json', 'html']) === 'html';
|
318 | }
|
319 |
|
320 |
|
321 |
|
322 |
|
323 |
|
324 | function sendResponse(response, type, data) {
|
325 | const chunk = Buffer.from(data, 'utf8');
|
326 | response.setHeader('Content-Type', type + '; charset=utf-8');
|
327 | response.setHeader('Content-Length', String(chunk.length));
|
328 | response.end(chunk);
|
329 | }
|