-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponses.ts
302 lines (265 loc) · 7.13 KB
/
responses.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
import {
executeSync,
ExecutionResult,
getOperationAST,
GraphQLArgs,
GraphQLError,
isString,
isUndefined,
jsonObject,
parse,
specifiedRules,
Status,
stringify,
tryCatchSync,
validate,
} from "./deps.ts";
import { ApplicationGraphQLJson, ApplicationJson, Result } from "./types.ts";
import { APPLICATION_GRAPHQL_JSON, APPLICATION_JSON } from "./constants.ts";
import { mergeInit } from "./utils.ts";
export type Params = {
mimeType: ApplicationGraphQLJson | ApplicationJson;
} & ExecutionResult;
export function createResponseFromResult(
{ mimeType, errors, extensions, data }: Params,
): [data: Response] | [data: undefined, err: TypeError] {
const [resultStr, err] = stringify({ errors, extensions, data });
if (err) {
return [, err];
}
switch (mimeType) {
case APPLICATION_JSON: {
return [
new Response(resultStr, {
status: Status.OK,
headers: {
"content-type": withCharset(mimeType),
},
}),
];
}
case APPLICATION_GRAPHQL_JSON: {
const status = isUndefined(data) ? Status.BadRequest : Status.OK;
return [
new Response(resultStr, {
status,
headers: {
"content-type": withCharset(mimeType),
},
}),
];
}
}
}
export function withCharset<T extends string>(value: T): `${T}; charset=UTF-8` {
return `${value}; charset=UTF-8`;
}
import { PickPartial, PickRequired } from "./deps.ts";
type ResponseParams = PickRequired<GraphQLArgs> & {
method: "GET" | "POST";
};
type ResponseOptions = PickPartial<GraphQLArgs> & {
mimeType: ApplicationGraphQLJson | ApplicationJson;
};
/**
* Create a GraphQL over HTTP compliant `Response` object.
* ```ts
* import {
* createResponse,
* } from "https://deno.land/x/graphql_http@$VERSION/mod.ts";
* import { buildSchema } from "https://esm.sh/graphql@$VERSION";
*
* const schema = buildSchema(`query {
* hello: String!
* }`);
*
* const res = createResponse({
* schema,
* source: `query { hello }`,
* method: "POST",
* }, {
* rootValue: {
* hello: "world",
* },
* });
* ```
*/
export function createResponse(
{ source, method, schema }: Readonly<ResponseParams>,
{
operationName,
variableValues,
rootValue,
contextValue,
fieldResolver,
typeResolver,
mimeType = "application/graphql+json",
}: Readonly<Partial<ResponseOptions>> = {},
): Response {
const ContentType = withCharset(mimeType);
const errorStatus = getErrorStatus(mimeType);
const parseResult = tryCatchSync(() => parse(source));
if (!parseResult[0]) {
const result = createResult(parseResult[1]);
const res = createJSONResponse(result, {
status: errorStatus,
headers: {
"content-type": ContentType,
},
});
return res;
}
const documentAST = parseResult[0];
const operationAST = getOperationAST(documentAST, operationName);
if (
method === "GET" && operationAST && operationAST.operation !== "query"
) {
const result = createResult(
`Invalid GraphQL operation. Can only perform a ${operationAST.operation} operation from a POST request.`,
);
const res = createJSONResponse(result, {
status: Status.MethodNotAllowed,
headers: {
"content-type": ContentType,
allow: "POST",
},
});
return res;
}
const validationErrors = validate(schema, documentAST, specifiedRules);
if (validationErrors.length > 0) {
const result: ExecutionResult = { errors: validationErrors };
const res = createJSONResponse(result, {
status: errorStatus,
headers: {
"content-type": ContentType,
},
});
return res;
}
const [executionResult, executionErrors] = tryCatchSync(() =>
executeSync({
schema,
document: documentAST,
operationName,
variableValues,
rootValue,
contextValue,
fieldResolver,
typeResolver,
})
);
if (executionResult) {
const [data, err] = createResponseFromResult({
mimeType,
...executionResult,
});
if (!data) {
const result = createResult(err);
const res = createJSONResponse(result, {
status: Status.InternalServerError,
headers: {
"content-type": ContentType,
},
});
return res;
}
return data;
}
const result = createResult(executionErrors);
const res = createJSONResponse(result, {
status: Status.InternalServerError,
headers: {
"content-type": ContentType,
},
});
return res;
}
export function createResult(error: unknown): ExecutionResult {
const graphqlError = resolveError(error);
const result: ExecutionResult = { errors: [graphqlError] };
return result;
}
export function createJSONResponse(
result: ExecutionResult,
responseInit: ResponseInit,
): Response {
const [data, err] = stringify(result);
if (err) {
const result = createResult(err);
const [body] = JSON.stringify(result);
const init = mergeInit(responseInit, {
status: Status.InternalServerError,
});
return new Response(body, init[0]);
}
const response = new Response(data, responseInit);
return response;
}
// When "Content-Type" is `application/json`, all Request error should be `200` status code. @see https://graphql.github.io/graphql-over-http/draft/#sec-application-json
// Validation error is Request error. @see https://spec.graphql.org/draft/#sec-Errors.Request-errors
function getErrorStatus(
mediaType: "application/graphql+json" | "application/json",
): number {
return mediaType === "application/json" ? Status.OK : Status.BadRequest;
}
function resolveError(er: unknown): GraphQLError {
if (er instanceof GraphQLError) return er;
if (isString(er)) return new GraphQLError(er);
return er instanceof Error
? new GraphQLError(
er.message,
undefined,
undefined,
undefined,
undefined,
er,
)
: new GraphQLError("Unknown error has occurred.");
}
/**
* Resolve GraphQL over HTTP response safety.
* @param res `Response` object
* @throws Error
* @throws AggregateError
* @throws SyntaxError
* @throws TypeError
* ```ts
* import {
* resolveResponse,
* } from "https://deno.land/x/graphql_http@$VERSION/mod.ts";
*
* const res = new Response(); // any Response
* const result = await resolveResponse(res);
* ```
*/
export async function resolveResponse<T extends jsonObject>(
res: Response,
): Promise<Result<T>> {
const contentType = res.headers.get("content-type");
if (!contentType) {
throw Error(`"Content-Type" header is required`);
}
if (!isValidContentType(contentType)) {
throw Error(
`Valid "Content-Type" is application/graphql+json or application/json`,
);
}
const json = await res.json() as Result<T>;
if (res.ok) {
return json;
} else {
if (json.errors) {
throw new AggregateError(
json.errors,
"GraphQL request error has occurred",
);
}
throw Error("Unknown error has occurred");
}
}
export function isValidContentType(value: string): boolean {
return ["application/json", "application/graphql+json"].some((mimeType) =>
value.includes(mimeType)
);
}