-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathAsync.ts
65 lines (52 loc) · 2 KB
/
Async.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
import type { Fetcher } from "graphql-ts-client-api";
import { TextWriter, util } from "graphql-ts-client-api";
export type GraphQLExecutor = (request: string, variables: object) => Promise<any>;
export function setGraphQLExecutor(executor: GraphQLExecutor) {
graphQLExecutor = executor;
}
export async function execute<TData extends object, TVariables extends object>(
fetcher: Fetcher<"Query" | "Mutation", TData, TVariables>,
options?: {
readonly operationName?: string,
readonly variables?: TVariables,
readonly executor?: GraphQLExecutor
}
) : Promise<TData> {
const executor = options?.executor ?? graphQLExecutor;
if (executor === undefined) {
throw new Error("Executor not set. Call 'setGraphQLExecutor' first or pass executor in options.");
}
const writer = new TextWriter();
writer.text(`${fetcher.fetchableType.name.toLowerCase()} ${options?.operationName ?? ''}`);
if (fetcher.variableTypeMap.size !== 0) {
writer.scope({type: "ARGUMENTS", multiLines: fetcher.variableTypeMap.size > 2, suffix: " "}, () => {
util.iterateMap(fetcher.variableTypeMap, ([name, type]) => {
writer.seperator();
writer.text(`$${name}: ${type}`);
});
});
}
writer.text(fetcher.toString());
writer.text(fetcher.toFragmentString());
const rawResponse = util.exceptNullValues(await executor(writer.toString(), options?.variables ?? {}));
if (rawResponse.errors) {
throw new GraphQLError(rawResponse.errors);
}
return rawResponse.data as TData;
}
export interface Response<TData> {
readonly data?: TData;
readonly error?: Error;
}
export class GraphQLError extends Error {
readonly errors: readonly GraphQLSubError[];
constructor(errors: any) {
super();
this.errors = errors;
}
}
export interface GraphQLSubError {
readonly message: string,
readonly path: string[]
}
let graphQLExecutor: GraphQLExecutor | undefined = undefined;