-
Notifications
You must be signed in to change notification settings - Fork 384
/
graphql-definitions.factory.ts
86 lines (82 loc) 路 2.48 KB
/
graphql-definitions.factory.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
85
86
import { isEmpty } from '@nestjs/common/utils/shared.utils';
import { gql, makeExecutableSchema } from 'apollo-server-express';
import * as chokidar from 'chokidar';
import { printSchema } from 'graphql';
import { GraphQLAstExplorer } from './graphql-ast.explorer';
import { GraphQLTypesLoader } from './graphql-types.loader';
import { removeTempField } from './utils/remove-temp.util';
export class GraphQLDefinitionsFactory {
private readonly gqlAstExplorer = new GraphQLAstExplorer();
private readonly gqlTypesLoader = new GraphQLTypesLoader();
async generate(options: {
typePaths: string[];
path: string;
outputAs?: 'class' | 'interface';
watch?: boolean;
debug?: boolean;
}) {
const isDebugEnabled = !(options && options.debug === false);
const typePathsExists = options.typePaths && !isEmpty(options.typePaths);
if (!typePathsExists) {
throw new Error(`"typePaths" property cannot be empty.`);
}
if (options.watch) {
this.printMessage(
'GraphQL factory is watching your files...',
isDebugEnabled,
);
const watcher = chokidar.watch(options.typePaths);
watcher.on('change', async file => {
this.printMessage(
`[${new Date().toLocaleTimeString()}] "${file}" has been changed.`,
isDebugEnabled,
);
await this.exploreAndEmit(
options.typePaths,
options.path,
options.outputAs,
isDebugEnabled,
);
});
}
await this.exploreAndEmit(
options.typePaths,
options.path,
options.outputAs,
isDebugEnabled,
);
}
private async exploreAndEmit(
typePaths: string[],
path: string,
outputAs: 'class' | 'interface',
isDebugEnabled: boolean,
) {
const typeDefs = await this.gqlTypesLoader.mergeTypesByPaths(
typePaths || [],
);
if (!typeDefs) {
throw new Error(`"typeDefs" property cannot be null.`);
}
let schema = makeExecutableSchema({
typeDefs,
resolverValidationOptions: { allowResolversNotInSchema: true },
});
schema = removeTempField(schema);
const tsFile = this.gqlAstExplorer.explore(
gql`
${printSchema(schema)}
`,
path,
outputAs,
);
await tsFile.save();
this.printMessage(
`[${new Date().toLocaleTimeString()}] The definitions have been updated.`,
isDebugEnabled,
);
}
private printMessage(text: string, isEnabled: boolean) {
isEnabled && console.log(text);
}
}