-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathassertKoaContextRequestGraphQL.mjs
76 lines (67 loc) · 2.12 KB
/
assertKoaContextRequestGraphQL.mjs
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
// @ts-check
import createHttpError from "http-errors";
/**
* Asserts that a Koa context has a correctly structured GraphQL request body.
* @template [KoaContextState=import("koa").DefaultState]
* @template [KoaContext=import("koa").DefaultContext]
* @param {import("koa").ParameterizedContext<
* KoaContextState,
* KoaContext
* >} koaContext Koa context.
* @returns {asserts koaContext is KoaContextRequestGraphQL<
* KoaContextState,
* KoaContext
* >}
*/
export default function assertKoaContextRequestGraphQL(koaContext) {
if (typeof koaContext.request.body === "undefined")
throw createHttpError(500, "Request body missing.");
if (
typeof koaContext.request.body !== "object" ||
koaContext.request.body == null ||
Array.isArray(koaContext.request.body)
)
throw createHttpError(400, "Request body must be a JSON object.");
if (!("query" in koaContext.request.body))
throw createHttpError(400, "GraphQL operation field `query` missing.");
const body = /** @type {{ [key: string]: unknown }} */ (
koaContext.request.body
);
if (typeof body.query !== "string")
throw createHttpError(
400,
"GraphQL operation field `query` must be a string."
);
if (
body.operationName != undefined &&
body.operationName != null &&
typeof body.operationName !== "string"
)
throw createHttpError(
400,
"Request body JSON `operationName` field must be a string."
);
if (
body.variables != undefined &&
body.variables != null &&
(typeof body.variables !== "object" || Array.isArray(body.variables))
)
throw createHttpError(
400,
"Request body JSON `variables` field must be an object."
);
}
/**
* @template [KoaContextState=import("koa").DefaultState]
* @template [KoaContext=import("koa").DefaultContext]
* @typedef {import("koa").ParameterizedContext<KoaContextState, KoaContext> & {
* request: {
* body: {
* query: string,
* operationName?: string | null,
* variables?: { [variableName: string]: unknown } | null,
* [key: string]: unknown,
* }
* }
* }} KoaContextRequestGraphQL
*/