-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
76 lines (60 loc) · 2.1 KB
/
plugin.ts
File metadata and controls
76 lines (60 loc) · 2.1 KB
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
import { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
import { capitalCase } from 'change-case-all';
import { concatAST, DirectiveNode, DocumentNode, GraphQLSchema, visit } from 'graphql';
interface NamedOperationsObjectPluginConfig {
fragmentRegistryName?: string
fragmentRegistryDirective?: string
omitOperationSuffix?: boolean
}
function filterByDirective(directives: readonly DirectiveNode[] | undefined, needed: string | undefined) {
// if no restriction specified then list all
if (!needed) return true
// TODO: Investigate under what circumstances can it actually be undefined?
/* istanbul ignore next */
if (!directives) return false
for (let index = 0; index < directives.length; index++) {
const directive = directives[index]
if (directive.name.value === needed) {
return true
}
}
// if nothing matched then we ignore this fragment
return false
}
export const plugin: PluginFunction<NamedOperationsObjectPluginConfig, string> = (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config: NamedOperationsObjectPluginConfig
) => {
const fragmentRegistryName = config.fragmentRegistryName || 'FragmentRegistry'
const docs = documents.map(v => v.document) as DocumentNode[]
const allAst = concatAST(docs);
const fragments: string[] = []
visit(allAst, {
FragmentDefinition: node => {
if (filterByDirective(node.directives, config.fragmentRegistryDirective)) {
fragments.push(node.name.value)
}
},
});
const suffix = (config.omitOperationSuffix) ? '' : 'Fragment'
const source = []
// Wrapper type
source.push(`export type StackablesEnvelope<T> = {
version: "0.1"
payload: T
params: any
callback: {
url: string
token: string
}
}`)
// Handler functions
fragments.map(fragment => {
source.push(`export type ${fragment}Handler = StackablesEnvelope<${fragment}${suffix}>`)
})
source.push(`export type ${fragmentRegistryName} = {
${fragments.map(fragment => ` 'stackables.webhook.${fragment}': ${fragment}Handler`).join('\n')}
}`)
return source.join('\n')
};