-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequests.ts
438 lines (389 loc) · 10.1 KB
/
requests.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import {
APPLICATION_GRAPHQL_JSON,
APPLICATION_JSON,
MIME_TYPE_APPLICATION_JSON,
} from "./constants.ts";
import {
accepts,
createHttpError,
HttpError,
isNil,
isNull,
isObject,
isString,
JSON,
jsonObject,
parseMediaType,
Status,
stringify,
tryCatchSync,
} from "./deps.ts";
import { GraphQLParameters } from "./types.ts";
const ACCEPT = `${APPLICATION_GRAPHQL_JSON}, ${APPLICATION_JSON}` as const;
export type Params = {
/** GraphQL query. */
query: string;
/** GraphQL URL endpoint. */
url: URL | string;
};
export type Options = {
/** GraphQL variables. */
variables: jsonObject;
/** HTTP Request method.
* According to the GraphQL over HTTP Spec, all GraphQL servers accept `POST` requests.
* @default `POST`
*/
// deno-lint-ignore ban-types
method: "GET" | "POST" | ({} & string);
/** GraphQL operation name. */
operationName: string;
};
/** Create GraphQL `Request` object.
* @param params parameters.
* @param options options.
* ```ts
* import { createRequest } from "https://deno.land/x/graphql_http@$VERSION/mod.ts";
*
* const [request, err] = createRequest({
* url: "<graphql-endpoint>",
* query: `query Greet(name: $name) {
* hello(name: $name)
* }`,
* method: "GET",
* });
*
* if (!err) {
* const res = await fetch(request);
* }
* ```
*/
export function createRequest(
params: Readonly<Params & Pick<Options, "method">>,
options: Partial<Omit<Options, "method">> = {},
): [data: Request, error: undefined] | [data: undefined, error: TypeError] {
const [data, err] = createRequestInitSet(params, options);
if (err) {
return [, err];
}
const requestResult = tryCatchSync(() =>
new Request(data.url.toString(), data.requestInit)
);
return requestResult as [Request, undefined] | [undefined, TypeError];
}
export function createRequestInitSet(
{ url: _url, query, method }: Readonly<Params & Pick<Options, "method">>,
{ variables, operationName }: Partial<Options>,
):
| [data: { url: URL; requestInit: RequestInit }, error: undefined]
| [data: undefined, error: TypeError] {
const [url, err] = isString(_url)
? tryCatchSync(() => new URL(_url))
: [_url, undefined] as const;
if (!url) {
return [, err as TypeError];
}
switch (method) {
case "GET": {
const result = addQueryString(url, {
query,
operationName,
variables,
});
if (result[1]) {
return [undefined, result[1]];
}
const requestInit: RequestInit = {
method,
headers: {
Accept: ACCEPT,
},
};
return [{ url: result[0], requestInit }, undefined];
}
case "POST": {
const [body, err] = stringify({ query, variables, operationName });
if (err) {
return [, err];
}
const requestInit: RequestInit = {
method,
body,
headers: {
accept: ACCEPT,
"content-type": MIME_TYPE_APPLICATION_JSON,
},
};
return [{ url, requestInit }, undefined];
}
default: {
return [{ url, requestInit: {} }, undefined];
}
}
}
function addQueryString(
url: URL,
{ query, variables, operationName }:
& Pick<Params, "query">
& Partial<Pick<Options, "operationName" | "variables">>,
): [data: URL, error: undefined] | [data: undefined, error: TypeError] {
url.searchParams.set("query", query);
if (variables) {
const [data, err] = stringify(variables);
if (err) {
return [, err];
}
url.searchParams.set("variables", data);
}
if (operationName) {
url.searchParams.set("operationName", operationName);
}
return [url, undefined];
}
export type RequestResult = [data: GraphQLParameters] | [
data: undefined,
error: HttpError,
];
/** Resolve GraphQL over HTTP request, take out GraphQL parameters safety.
* @params req `Request` object
* @remark No error is thrown and `reject` is never called.
* ```ts
* import {
* resolveRequest,
* } from "https://deno.land/x/graphql_http@$VERSION/mod.ts";
*
* const req = new Request("<graphql-endpoint>"); // any Request
* const [data, err] = await resolveRequest(req);
* if (data) {
* const { query, variableValues, operationName, extensions } = data;
* }
* ```
*/
export function resolveRequest(
req: Request,
): RequestResult | Promise<RequestResult> {
const method = req.method;
switch (method) {
case "GET": {
return resolveGetRequest(req);
}
case "POST": {
return resolvePostRequest(req);
}
default: {
return [
,
createHttpError(
Status.MethodNotAllowed,
`Invalid HTTP method. GraphQL only supports GET and POST requests.`,
),
];
}
}
}
export function resolveGetRequest(req: Request): RequestResult {
const acceptResult = resolveAcceptHeader(req);
if (acceptResult[1]) {
return acceptResult;
}
const url = new URL(req.url);
const source = url.searchParams.get("query");
if (!source) {
return [
,
createHttpError(Status.BadRequest, `The parameter is required. "query"`),
];
}
let variableValues: GraphQLParameters["variableValues"] | null = null;
const variables = url.searchParams.get("variables");
if (isString(variables)) {
const [data, err] = JSON.parse(variables);
if (err) {
return [
,
createHttpError(
Status.BadRequest,
`The parameter is invalid. "variables" are invalid JSON.`,
),
];
}
if (isPlainObject(data)) {
variableValues = data;
}
}
const operationName = url.searchParams.get("operationName");
return [{
query: source,
variableValues,
operationName,
extensions: null,
}];
}
export async function resolvePostRequest(
req: Request,
): Promise<RequestResult> {
const acceptHeader = resolveAcceptHeader(req);
if (acceptHeader[1]) {
return acceptHeader;
}
const contentType = req.headers.get("content-type");
if (!contentType) {
return [
,
createHttpError(
Status.BadRequest,
`The header is required. "Content-Type"`,
),
];
}
const [mediaType, record = { charset: "UTF-8" }] = parseMediaType(
contentType,
);
const charset = record.charset ? record.charset : "UTF-8";
if (charset.toUpperCase() !== "UTF-8") {
return [
,
createHttpError(
Status.UnsupportedMediaType,
`The header is invalid. Supported media type charset is "UTF-8".`,
),
];
}
// // TODO:(miyauci) check the body already read.
// const body = await req.text();
switch (mediaType) {
case "application/json": {
const data = await req.text();
const [json, err] = JSON.parse(data);
if (err) {
return [
,
createHttpError(
Status.BadRequest,
`The message body is invalid. Invalid JSON format.`,
),
];
}
if (!isPlainObject(json)) {
return [
,
createHttpError(
Status.BadRequest,
`The message body is invalid. Must be JSON object format.`,
),
];
}
const { query: _query, operationName = null, variables = null } = json;
const query = isNil(_query)
? new URL(req.url).searchParams.get("query")
: _query;
if (isNil(query)) {
return [
,
createHttpError(
Status.BadRequest,
`The parameter is required. "query"`,
),
];
}
if (!isString(query)) {
return [
,
createHttpError(
Status.BadRequest,
`The parameter is invalid. "query" must be string.`,
),
];
}
if (!isNull(variables) && !isPlainObject(variables)) {
return [
,
createHttpError(
Status.BadRequest,
`The parameter is invalid. "variables" must be JSON object format`,
),
];
}
if (!isStringOrNull(operationName)) {
return [
,
createHttpError(
Status.BadRequest,
`The parameter is invalid. "operationName" must be string or null.`,
),
];
}
return [{
query,
operationName,
variableValues: variables,
extensions: null,
}];
}
case "application/graphql+json": {
const body = await req.text();
const fromQueryString = new URL(req.url).searchParams.get("query");
const query = !body ? fromQueryString : body;
if (!query) {
return [
,
createHttpError(
Status.BadRequest,
`The message body is required. "GraphQL query"`,
),
];
}
return [{
query,
operationName: null,
variableValues: null,
extensions: null,
}];
}
default: {
return [
,
createHttpError(
Status.UnsupportedMediaType,
`The header is invalid. "Content-Type" must be "application/json" or "application/graphql+json"`,
),
];
}
}
}
function resolveAcceptHeader(
req: Request,
): [data: string, error: undefined] | [
data: undefined,
error: HttpError,
] {
// Accept header is not provided, treat the request has `Accept: application/json`
// From 1st January 2025 (2025-01-01T00:00:00Z), treat the request has `Accept: application/graphql+json`
// @see https://graphql.github.io/graphql-over-http/draft/#sec-Legacy-watershed
if (!req.headers.has("accept")) {
return [
"application/json",
undefined,
];
}
const acceptResult = accepts(
req,
"application/graphql+json",
"application/json",
);
if (!acceptResult) {
return [
,
createHttpError(
Status.NotAcceptable,
`The header is invalid. "Accept" must include "application/graphql+json" or "application/json"`,
),
];
}
return [acceptResult, undefined];
}
function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {
return isObject(value) && value.constructor === Object;
}
function isStringOrNull(value: unknown): value is string | null {
return isString(value) || isNull(value);
}