-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathschema.ts
92 lines (82 loc) · 2.57 KB
/
schema.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
87
88
89
90
91
92
import fs from 'fs-extra';
import * as graphql from 'graphql/language/index.js';
import type { DocumentNode } from 'graphql/language/index.js';
import SchemaCodeGenerator from './codegen/schema.js';
export default class Schema {
constructor(
public document: string,
public ast: DocumentNode,
public filename?: string,
) {
this.filename = filename;
this.document = document;
this.ast = ast;
}
codeGenerator() {
return new SchemaCodeGenerator(this);
}
static async load(filename: string) {
const document = await fs.readFile(filename, 'utf-8');
const ast = graphql.parse(document);
return new Schema(document, ast, filename);
}
static async loadFromString(document: string) {
try {
const ast = graphql.parse(document);
return new Schema(document, ast);
} catch (e) {
throw new Error(`Failed to load schema from string: ${e.message}`);
}
}
getEntityNames(): string[] {
return this.ast.definitions
.filter(
def =>
def.kind === 'ObjectTypeDefinition' &&
def.directives?.find(directive => directive.name.value === 'entity') !== undefined,
)
.map(entity => (entity as graphql.ObjectTypeDefinitionNode).name.value);
}
immutableEntitiesCount(): number {
const isImmutable = (entity: graphql.ConstDirectiveNode) => {
return (
entity.arguments?.find(arg => {
return (
(arg.name.value === 'immutable' || arg.name.value === 'timeseries') &&
arg.value.kind === 'BooleanValue' &&
arg.value.value
);
}) !== undefined
);
};
return this.ast.definitions.filter(def => {
if (def.kind !== 'ObjectTypeDefinition') {
return false;
}
const entity = def.directives?.find(directive => directive.name.value === 'entity');
if (entity === undefined) {
return false;
}
return isImmutable(entity);
}).length;
}
getImmutableEntityNames(): string[] {
return this.ast.definitions
.filter(
def =>
def.kind === 'ObjectTypeDefinition' &&
def.directives?.find(
directive =>
directive.name.value === 'entity' &&
directive.arguments?.find(arg => {
return (
arg.name.value === 'immutable' &&
arg.value.kind === 'BooleanValue' &&
arg.value.value === true
);
}),
) !== undefined,
)
.map(entity => (entity as graphql.ObjectTypeDefinitionNode).name.value);
}
}