/
adapter-fixture.ts
75 lines (70 loc) · 2.7 KB
/
adapter-fixture.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
import ts from 'typescript';
import { GraphQLSchema } from 'graphql';
import {
createScriptSourceHelper,
getTemplateNodeUnder,
getSanitizedTemplateText,
ScriptSourceHelper,
} from '../../ts-ast-util';
import { FragmentRegistry } from '../../gql-ast-util';
import { GraphQLLanguageServiceAdapter } from '../graphql-language-service-adapter';
import {
createTestingLanguageServiceAndHost,
TestingLanguageServiceHost,
} from '../../ts-ast-util/testing/testing-language-service';
export class AdapterFixture {
readonly adapter: GraphQLLanguageServiceAdapter;
readonly langService: ts.LanguageService;
readonly scriptSourceHelper: ScriptSourceHelper;
private readonly _sourceFileName: string;
private readonly _langServiceHost: TestingLanguageServiceHost;
private readonly _fragmentRegistry: FragmentRegistry;
constructor(sourceFileName: string, schema?: GraphQLSchema) {
const { languageService, languageServiceHost } = createTestingLanguageServiceAndHost({
files: [{ fileName: sourceFileName, content: '' }],
});
this._sourceFileName = sourceFileName;
this._langServiceHost = languageServiceHost;
this._fragmentRegistry = new FragmentRegistry();
this.langService = languageService;
(this.scriptSourceHelper = createScriptSourceHelper(
{ languageService, languageServiceHost, project: { getProjectName: () => 'tsconfig.json' } },
{ exclude: [] },
)),
(this.adapter = new GraphQLLanguageServiceAdapter(this.scriptSourceHelper, {
schema: schema || null,
removeDuplicatedFragments: true,
fragmentRegistry: this._fragmentRegistry,
tag: {
names: [],
allowNotTaggedTemplate: true,
allowTaggedTemplateExpression: true,
allowFunctionCallExpression: true,
},
}));
}
get source() {
return this._langServiceHost.getFile(this._sourceFileName)!.content;
}
set source(content: string) {
this._langServiceHost.updateFile(this._sourceFileName, content);
const documents = this.scriptSourceHelper
.getAllNodes(this._sourceFileName, node =>
getTemplateNodeUnder(node, {
names: [],
allowNotTaggedTemplate: true,
allowTaggedTemplateExpression: true,
allowFunctionCallExpression: true,
}),
)
.map(node => getSanitizedTemplateText(node));
this._fragmentRegistry.registerDocuments(this._sourceFileName, content, documents);
}
registerFragment(sourceFileName: string, fragmentDefDoc: string) {
if (sourceFileName === this._sourceFileName) return this;
this._fragmentRegistry.registerDocuments(sourceFileName, fragmentDefDoc, [
{ sourcePosition: 0, text: fragmentDefDoc },
]);
return this;
}
}