-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathschema-loader.ts
40 lines (30 loc) · 1.19 KB
/
schema-loader.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
import fs from 'fs';
import { ObjectTypeDefinitionNode, TypeNode, DocumentNode } from 'graphql';
import { join } from 'path';
import { parse } from 'graphql/language/parser';
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));
}
return new SchemaLoader(schema);
}
}