-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate-gql-types.ts
More file actions
159 lines (136 loc) · 5.23 KB
/
generate-gql-types.ts
File metadata and controls
159 lines (136 loc) · 5.23 KB
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
import CodeBlockWriter from "code-block-writer";
import type { ServerSideFetch } from "@aklinker1/zeta/types";
import app from "../src/server";
import { createLogger } from "@aklinker1/logger";
const logger = createLogger("gen:gql-types");
const typesFile = Bun.file("src/@types/gql.d.ts");
const scalarNameToTs = {
Boolean: "bool",
String: "string",
Int: "number",
Float: "number",
};
export async function generateGqlTypes(fetch: ServerSideFetch = app.build()) {
logger.info("Starting...");
const introspection = await introspect(fetch);
const {
queryType,
mutationType,
subscriptionType,
types,
directives: _,
} = introspection.data.__schema;
let argTypes: any[] = [];
const code = new CodeBlockWriter({
indentNumberOfSpaces: 2,
newLine: "\n",
});
code.write("namespace Gql").block(() => {
// Root Resolver Type
const rootTypeNames = [
queryType?.name,
mutationType?.name,
subscriptionType?.name,
].filter((name) => !!name);
code.writeLine(`type RootResolver = ${rootTypeNames.join(" | ")}`);
// Types
types.forEach((type: any) => {
// Ignore internal types
if (type.name.startsWith("__")) return;
switch (type.kind) {
case "OBJECT":
return writeObjectType(code, argTypes, type);
case "SCALAR":
return writeScalarType(code, type);
case "INTERFACE":
return writeObjectType(code, argTypes, type);
default:
return logger.warn("Unknown kind:", {
kind: type.kind,
name: type.name,
});
}
});
// Query Variables
argTypes.map((type) => writeObjectType(code, argTypes, type));
});
code.newLine();
await Bun.write(typesFile, code.toString());
logger.success("Done");
}
function capitalizeFirstLetter(str: string): string {
if (str.length === 0) return str;
return str[0]!.toUpperCase() + str.substring(1);
}
function getTsTypeString(gqlType: any, isReturn?: boolean): string {
if (gqlType.kind === "NON_NULL")
return getTsTypeString(gqlType.ofType, isReturn).replace(
" | undefined",
"",
);
if (gqlType.kind === "LIST")
return `Array<${getTsTypeString(gqlType.ofType, isReturn)}> | undefined`;
if (gqlType.kind === "SCALAR" || gqlType.kind === "OBJECT")
return `${gqlType.name}${isReturn ? " | Error" : ""} | undefined`;
logger.warn("Unknown GQL -> TS type", { gqlType });
return "unknown";
}
function writeCommentBlock(code: CodeBlockWriter, description: string | null) {
if (!description) return;
code.writeLine("/**");
description
?.split("\n")
.forEach((line: string) => code.writeLine(` * ${line}`));
code.writeLine(" */");
}
function writeObjectType(code: CodeBlockWriter, argTypes: any[], type: any) {
writeCommentBlock(code, type.description);
code.write(`interface ${type.name}`).block(() => {
type.fields.forEach((field: any) => {
writeCommentBlock(code, field.description);
let returnTypeStr = getTsTypeString(field.type);
let args = "";
if (field.args?.length) {
const argsType = {
kind: "OBJECT",
name: `${type.name}${capitalizeFirstLetter(field.name)}Variables`,
fields: field.args,
};
args = `(args: ${argsType.name}, ctx: WxtQueueCtx)`;
argTypes.push(argsType);
returnTypeStr = getTsTypeString(field.type, true);
returnTypeStr = `Promise<${returnTypeStr}> | ${returnTypeStr}`;
}
code.writeLine(`"${field.name}"${args}: ${returnTypeStr}`);
});
});
}
function writeScalarType(code: CodeBlockWriter, type: any) {
writeCommentBlock(code, type.description);
// @ts-expect-error
const typeStr = scalarNameToTs[type.name];
if (typeStr == null) {
logger.warn("Unknown scalar type:", { type });
}
code.writeLine(`type ${type.name} = ${typeStr || "unknown"};`);
}
async function introspect(fetch: ServerSideFetch): Promise<any> {
const request = new Request("http://localhost/api", {
body: JSON.stringify({
operationName: "IntrospectionQuery",
query:
"query IntrospectionQuery { __schema { queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } directives { name description locations args { ...InputValue } } } } fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } } } ",
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const res = await fetch(request);
if (!res.ok)
throw Error("Introspection request failed: " + (await res.text()));
const json: any = await res.json();
if (json.errors)
throw Error("Introspection request failed: " + JSON.stringify(json.errors));
return json;
}