/
index.ts
226 lines (204 loc) · 6.33 KB
/
index.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { extname } from 'path';
import { PluginFunction, PluginValidateFn, Types, removeFederation } from '@graphql-codegen/plugin-helpers';
import { GraphQLSchema, execute, parse } from 'graphql';
interface IntrospectionResultData {
__schema: {
types: {
kind: string;
name: string;
possibleTypes:
| {
name: string;
}[]
| null;
}[];
};
}
interface PossibleTypesResultData {
possibleTypes: {
[key: string]: string[];
};
}
/**
* @description This plugin generates an introspection file but only with Interfaces and Unions, based on your GraphQLSchema.
*
* If you are using `apollo-client` and your schema contains `interface` or `union` declaration, it's recommended to use Apollo's Fragment Matcher and the result generated by the plugin.
*
* You can read more about it in `apollo-client` documentation: https://www.apollographql.com/docs/react/data/fragments/#fragments-on-unions-and-interfaces.
*
* Fragment Matcher plugin accepts a TypeScript / JavaScript or a JSON file as an output _(`.ts, .tsx, .js, .jsx, .json`)_.
*
* Both in TypeScript and JavaScript a default export is being used.
*
* > The output is based on the output you choose for the output file name.
*/
export interface FragmentMatcherConfig {
/**
* @description Compatible only with JSON extension, allow you to choose the export type, either `module.exports` or `export default`. Allowed values are: `commonjs`, `es2015`.
* @default es2015
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.json:
* plugins:
* - fragment-matcher
* config:
* module: commonjs
* ```
*/
module?: 'commonjs' | 'es2015';
/**
* @description Compatible only with TS/TSX/JS/JSX extensions, allow you to generate output based on your Apollo-Client version. Valid values are: `2`, `3`.
* @default 3
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - fragment-matcher
* config:
* apolloClientVersion: 3
* ```
*/
apolloClientVersion?: 2 | 3;
/**
* @description Create an explicit type based on your schema. This can help IDEs autofill your fragment matcher. This is mostly useful if you do more with your fragment matcher than just pass it to an Apollo-Client.
* @default false
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - fragment-matcher
* config:
* useExplicitTyping: true
* ```
*/
useExplicitTyping?: boolean;
federation?: boolean;
}
const extensions = {
ts: ['.ts', '.tsx'],
js: ['.js', '.jsx'],
json: ['.json'],
};
export const plugin: PluginFunction = async (
schema: GraphQLSchema,
_documents,
pluginConfig: FragmentMatcherConfig,
info
): Promise<string> => {
const config: Required<FragmentMatcherConfig> = {
module: 'es2015',
federation: false,
apolloClientVersion: 3,
useExplicitTyping: false,
...pluginConfig,
};
const apolloClientVersion = parseInt(config.apolloClientVersion as any);
const cleanSchema = config.federation ? removeFederation(schema) : schema;
const useExplicitTyping = config.useExplicitTyping;
const introspection = (await execute({
schema: cleanSchema,
document: parse(`
{
__schema {
types {
kind
name
possibleTypes {
name
}
}
}
}
`),
})) as any;
const ext = extname(info.outputFile).toLowerCase();
if (!introspection.data) {
throw new Error(`Plugin "fragment-matcher" couldn't introspect the schema`);
}
const filterUnionAndInterfaceTypes = type => type.kind === 'UNION' || type.kind === 'INTERFACE';
const createPossibleTypesCollection = (acc, type) => {
return { ...acc, ...{ [type.name]: type.possibleTypes.map(possibleType => possibleType.name) } };
};
const filteredData: IntrospectionResultData | PossibleTypesResultData =
apolloClientVersion === 2
? {
__schema: {
...introspection.data.__schema,
types: introspection.data.__schema.types.filter(type => type.kind === 'UNION' || type.kind === 'INTERFACE'),
},
}
: {
possibleTypes: introspection.data.__schema.types
.filter(filterUnionAndInterfaceTypes)
.reduce(createPossibleTypesCollection, {}),
};
const content = JSON.stringify(filteredData, null, 2);
if (extensions.json.includes(ext)) {
return content;
}
if (extensions.js.includes(ext)) {
const defaultExportStatement = config.module === 'es2015' ? `export default` : 'module.exports =';
return `
${defaultExportStatement} ${content}
`;
}
if (extensions.ts.includes(ext)) {
let typename: string;
if (apolloClientVersion === 2) {
typename = `IntrospectionResultData`;
} else if (apolloClientVersion === 3) {
typename = `PossibleTypesResultData`;
}
let type: string;
if (useExplicitTyping) {
type = `export type ${typename} = ${content};`;
} else if (apolloClientVersion === 2) {
type = `export interface ${typename} {
__schema: {
types: {
kind: string;
name: string;
possibleTypes: {
name: string;
}[];
}[];
};
}`;
} else if (apolloClientVersion === 3) {
type = `export interface ${typename} {
possibleTypes: {
[key: string]: string[]
}
}`;
}
return `
${type}
const result: ${typename} = ${content};
export default result;
`;
}
throw new Error(`Extension ${ext} is not supported`);
};
export const validate: PluginValidateFn<any> = async (
_schema: GraphQLSchema,
_documents: Types.DocumentFile[],
config: FragmentMatcherConfig,
outputFile: string
) => {
const ext = extname(outputFile).toLowerCase();
const all = Object.values(extensions).reduce((acc, exts) => [...acc, ...exts], []);
if (!all.includes(ext)) {
throw new Error(
`Plugin "fragment-matcher" requires extension to be one of ${all.map(val => val.replace('.', '')).join(', ')}!`
);
}
if (config.module === 'commonjs' && extensions.ts.includes(ext)) {
throw new Error(`Plugin "fragment-matcher" doesn't support commonjs modules combined with TypeScript!`);
}
};