-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathschema-loader.ts
More file actions
48 lines (38 loc) · 1.26 KB
/
schema-loader.ts
File metadata and controls
48 lines (38 loc) · 1.26 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
import fs from "fs";
import type { DocumentNode, ObjectTypeDefinitionNode } from "graphql";
import { join } from "path";
import { parse } from "graphql/language/parser.js";
const { readdir, readFile } = fs.promises;
export default class SchemaLoader {
originalTypeDefs: DocumentNode;
queryDef: ObjectTypeDefinitionNode;
resourceTypeDefs: Array<ObjectTypeDefinitionNode>;
constructor(graphql: string) {
this.originalTypeDefs = parse(graphql);
const typeDefinitionNodes = this.originalTypeDefs.definitions.filter(
(def): def is ObjectTypeDefinitionNode => {
return def.kind === "ObjectTypeDefinition";
}
);
const queryDef = typeDefinitionNodes.find(
(def) => def.name.value === "Query"
);
if (!queryDef) {
throw new Error("Query is not defined");
}
this.queryDef = queryDef;
this.resourceTypeDefs = typeDefinitionNodes.filter(
(def) => def.name.value !== "Query"
);
}
static async loadFrom(baseDir: string): Promise<SchemaLoader> {
let schema = "";
for (const path of await readdir(baseDir)) {
if (!/^[0-9a-zA-Z].*\.graphql$/.test(path)) {
continue;
}
schema += await readFile(join(baseDir, path), "utf8");
}
return new SchemaLoader(schema);
}
}