This repository was archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathcodegen.ts
More file actions
139 lines (124 loc) · 3.67 KB
/
codegen.ts
File metadata and controls
139 lines (124 loc) · 3.67 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
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
import {
GraphQLSchema,
concatAST,
Kind,
FragmentDefinitionNode,
OperationDefinitionNode,
} from "graphql";
import {
Types,
PluginFunction,
oldVisit,
} from "@graphql-codegen/plugin-helpers";
import {
ClientSideBaseVisitor,
LoadedFragment,
} from "@graphql-codegen/visitor-plugin-common";
import pascalCase from "just-pascal-case";
// The main codegen plugin.
export const plugin: PluginFunction<any> = (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config
) => {
// Get all graphql documents
const allAst = concatAST(documents.map((d) => d.document));
// Get all fragments
const allFragments: LoadedFragment[] = [
...(
allAst.definitions.filter(
(d) => d.kind === Kind.FRAGMENT_DEFINITION
) as FragmentDefinitionNode[]
).map((fragmentDef) => ({
node: fragmentDef,
name: fragmentDef.name.value,
onType: fragmentDef.typeCondition.name.value,
isExternal: false,
})),
...(config.externalFragments || []),
];
// Create the visitor
const visitor = new ClientSideBaseVisitor(
schema,
allFragments,
config,
{ documentVariableSuffix: "Doc" },
documents
);
// Visit all the documents
const visitorResult = oldVisit(allAst, { leave: visitor });
// Filter out the operations
const operations = allAst.definitions.filter(
(d) => d.kind === Kind.OPERATION_DEFINITION
) as OperationDefinitionNode[];
// The default required types. These should probably live somewhere else and be imported
// TODO: move to a file
const defaultTypes = `
type SubscribeWrapperArgs<T> = {
variables?: T,
fetch?: typeof fetch
}
interface CacheFunctionOptions {
update?: boolean
}
`;
// This is where the string that will be written to .gq files is created
const ops = operations
.map((o) => {
if (o) {
const name = o?.name?.value || "";
const op = `${pascalCase(name)}${pascalCase(o.operation)}`;
const pascalName = pascalCase(name);
const opv = `${op}Variables`;
let operations = "";
if (o.operation === "query") {
operations += `
export const ${name} = writable<GFetchReturnWithErrors<${op}>>({
errors: [],
gQueryStatus: 'LOADING',
})
// Cached
export async function get${pascalName}({ fetch, variables }: GGetParameters<${opv}>, options?: CacheFunctionOptions) {
const data = await g.fetch<${op}>({
queries: [{ query: ${pascalName}Doc, variables }],
fetch
})
${name}.set({ ...data, errors: data?.errors, gQueryStatus: 'LOADED' })
return data
}
`;
} else if (o.operation === "mutation") {
// This is where the mutation code is generated
// We're grabbing the mutation name and using it as a string in the generated code
operations += `
export const ${name} = ({ variables, fetch = window?.fetch }: SubscribeWrapperArgs<${opv}>):
Promise<GFetchReturnWithErrors<${op}>> =>
g.fetch<${op}>({
queries: [{ query: ${pascalName}Doc, variables }],
fetch,
})
`;
}
return operations;
}
})
.join("\n");
// The imports that are included at the top of the generated file
const imports = [
`import { writable } from "svelte/store"`,
`import { g } from '${config.gPath}'`,
`import type { GFetchReturnWithErrors, GGetParameters } from '@leveluptuts/g-query'`,
];
return {
prepend: [...imports, ...visitor.getImports()],
content: [
defaultTypes,
visitor.fragments,
...visitorResult.definitions.filter((t) => typeof t == "string"),
ops,
].join("\n"),
};
};
// TODO
// - add option to force update of cache. ie getUserTutorials({update: true})
// if update.true is not set, then it will only update if the cache is empty