-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgatsby-node.js
225 lines (206 loc) · 6.13 KB
/
gatsby-node.js
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
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const fs = require("fs-extra")
const fetch = require("node-fetch")
const path = require("path")
const { print } = require("gatsby/graphql")
const {
sourceAllNodes,
sourceNodeChanges,
createSchemaCustomization,
generateDefaultFragments,
compileNodeQueries,
buildNodeDefinitions,
wrapQueryExecutorWithQueue,
loadSchema,
} = require("gatsby-graphql-source-toolkit")
const craftGqlToken = process.env.CRAFTGQL_TOKEN
const craftGqlUrl = process.env.CRAFTGQL_URL
const fragmentsDir = __dirname + "/src/craft-fragments"
const debugDir = __dirname + "/.cache/craft-graphql-documents"
const gatsbyTypePrefix = `Craft_`
let schema
let gatsbyNodeTypes
let sourcingConfig
// 1. Gatsby field aliases
// 2. Node ID transforms?
// 3. Pagination strategies?
// 4. Schema customization field transforms?
// 5. Query variable provider?
async function getSchema() {
if (!schema) {
schema = await loadSchema(execute)
// schema = buildASTSchema(
// parse(fs.readFileSync(__dirname + "/schema.graphql").toString())
// )
}
return schema
}
async function getGatsbyNodeTypes() {
if (gatsbyNodeTypes) {
return gatsbyNodeTypes
}
const schema = await getSchema()
const fromIface = (ifaceName, doc) => {
const iface = schema.getType(ifaceName)
return schema.getPossibleTypes(iface).map(type => ({
remoteTypeName: type.name,
queries: doc(type.name),
}))
}
// prettier-ignore
return (gatsbyNodeTypes = [
...fromIface(`EntryInterface`, type => `
query LIST_${type} {
entries(type: "${type.split(`_`)[0]}", limit: $limit, offset: $offset) {
..._${type}_Id_
}
}
query NODE_${type} {
entry(type: "${type.split(`_`)[0]}", id: $id) {
..._${type}_Id_
}
}
fragment _${type}_Id_ on ${type} { __typename id }
`),
...fromIface(`AssetInterface`, type => `
query LIST_${type} {
assets(limit: $limit, offset: $offset) {
..._${type}_Id_
}
}
fragment _${type}_Id_ on ${type} { __typename id }
`),
...fromIface(`UserInterface`, type => `
query LIST_${type} {
users(limit: $limit, offset: $offset) {
..._${type}_Id_
}
}
fragment _${type}_Id_ on ${type} { __typename id }
`),
...fromIface(`TagInterface`, type => `
query LIST_${type} {
tags(limit: $limit, offset: $offset) {
..._${type}_Id_
}
}
fragment _${type}_Id_ on ${type} { __typename id }
`),
...fromIface(`GlobalSetInterface`, type => `
query LIST_${type} {
globalSets(limit: $limit, offset: $offset) {
..._${type}_Id_
}
}
fragment _${type}_Id_ on ${type} { __typename id }
`),
])
}
async function writeDefaultFragments() {
const defaultFragments = generateDefaultFragments({
schema: await getSchema(),
gatsbyNodeTypes: await getGatsbyNodeTypes(),
})
for (const [remoteTypeName, fragment] of defaultFragments) {
const filePath = path.join(fragmentsDir, `${remoteTypeName}.graphql`)
if (!fs.existsSync(filePath)) {
await fs.writeFile(filePath, fragment)
}
}
}
async function collectFragments() {
const customFragments = []
for (const fileName of await fs.readdir(fragmentsDir)) {
if (/.graphql$/.test(fileName)) {
const filePath = path.join(fragmentsDir, fileName)
const fragment = await fs.readFile(filePath)
customFragments.push(fragment.toString())
}
}
return customFragments
}
async function writeCompiledQueries(nodeDocs) {
await fs.ensureDir(debugDir)
for (const [remoteTypeName, document] of nodeDocs) {
await fs.writeFile(debugDir + `/${remoteTypeName}.graphql`, print(document))
}
}
async function getSourcingConfig(gatsbyApi, pluginOptions) {
if (sourcingConfig) {
return sourcingConfig
}
const schema = await getSchema()
const gatsbyNodeTypes = await getGatsbyNodeTypes()
const documents = await compileNodeQueries({
schema,
gatsbyNodeTypes,
customFragments: await collectFragments(),
})
await writeCompiledQueries(documents)
return (sourcingConfig = {
gatsbyApi,
schema,
gatsbyNodeDefs: buildNodeDefinitions({ gatsbyNodeTypes, documents }),
gatsbyTypePrefix,
execute: wrapQueryExecutorWithQueue(execute, { concurrency: 10 }),
verbose: true,
})
}
async function execute({ operationName, query, variables = {} }) {
// console.log(operationName, variables)
const res = await fetch(craftGqlUrl, {
method: "POST",
body: JSON.stringify({ query, variables, operationName }),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${craftGqlToken}`,
},
})
return await res.json()
}
exports.onPreBootstrap = async (gatsbyApi, pluginOptions) => {
await writeDefaultFragments()
}
exports.createSchemaCustomization = async (gatsbyApi, pluginOptions) => {
const config = await getSourcingConfig(gatsbyApi, pluginOptions)
await createSchemaCustomization(config)
}
exports.sourceNodes = async (gatsbyApi, pluginOptions) => {
const { cache } = gatsbyApi
const config = await getSourcingConfig(gatsbyApi, pluginOptions)
const cached = (await cache.get(`CRAFT_SOURCED`)) || false
if (cached) {
// Applying changes since the last sourcing
const nodeEvents = [
{
eventName: "DELETE",
remoteTypeName: "blog_blog_Entry",
remoteId: { __typename: "blog_blog_Entry", id: "422" },
},
{
eventName: "UPDATE",
remoteTypeName: "blog_blog_Entry",
remoteId: { __typename: "blog_blog_Entry", id: "421" },
},
{
eventName: "UPDATE",
remoteTypeName: "blog_blog_Entry",
remoteId: { __typename: "blog_blog_Entry", id: "18267" },
},
{
eventName: "UPDATE",
remoteTypeName: "blog_blog_Entry",
remoteId: { __typename: "blog_blog_Entry", id: "11807" },
},
]
console.log(`Sourcing delta!`)
await sourceNodeChanges(config, { nodeEvents })
return
}
await sourceAllNodes(config)
await cache.set(`CRAFT_SOURCED`, true)
}