-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathhttp.ts
84 lines (75 loc) · 1.94 KB
/
http.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
import Bluebird from "bluebird";
import request from "request";
import {
ApolloIntrospection,
GraphQLIntrospection,
Introspection,
Schema,
SchemaLoader,
} from "../interface";
import { query as introspectionQuery } from "../utility";
export interface IHttpSchemaLoaderOptions {
endpoint: string;
headers: string[];
queries: string[];
}
async function r(options: request.OptionsWithUrl) {
return new Bluebird<Schema>((resolve, reject) => {
request(options, (error, res, body: Introspection | string) => {
if (error) {
return reject(error);
}
if ((res.statusCode as number) >= 400) {
return reject(
new Error(
"Unexpected HTTP Status Code " +
res.statusCode +
" (" +
res.statusMessage +
") from: " +
options.url
)
);
}
if (typeof body === "string") {
return reject(
new Error(
'Unexpected response from "' +
options.url +
'": ' +
body.slice(0, 10) +
"..."
)
);
}
return resolve(
(body as ApolloIntrospection).__schema ||
(body as GraphQLIntrospection).data.__schema
);
});
});
}
export const httpSchemaLoader: SchemaLoader = async (
options: IHttpSchemaLoaderOptions
) => {
const requestOptions: request.OptionsWithUrl = {
url: options.endpoint,
method: "POST",
body: { query: introspectionQuery },
json: true,
};
requestOptions.headers = options.headers.reduce(
(result: any, header: string) => {
const [name, value] = header.split(": ", 2);
result[name] = value;
return result;
},
{}
);
requestOptions.qs = options.queries.reduce((result: any, query: string) => {
const [name, value] = query.split("=", 2);
result[name] = value;
return result;
}, {});
return r(requestOptions);
};