-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
370 lines (320 loc) · 12.7 KB
/
Copy pathgatsby-node.js
File metadata and controls
370 lines (320 loc) · 12.7 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const axios = require('axios');
const path = require('path');
const fs = require("fs");
const webpack = require('webpack');
const {createFilePath} = require('gatsby-source-filesystem');
const {fmImagesToRelative} = require('gatsby-remark-relative-images');
const {ClientCredentials} = require('simple-oauth2');
const URI = require('urijs');
const sizeOf = require('image-size');
const colorsFilepath = 'src/content/colors.json';
const disqusFilepath = 'src/content/disqus-settings.json';
const marketingFilepath = 'src/content/marketing-site.json';
const homeFilepath = 'src/content/home-settings.json';
const settingsFilepath = 'src/content/settings.json';
const myEnv = require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
const getAccessToken = async (config, scope) => {
const client = new ClientCredentials(config);
try {
return await client.getToken({ scope });
} catch (error) {
console.log('Access Token error', error);
}
};
const SSR_getMarketingSettings = async (baseUrl, summitId) => {
const params = {
per_page: 100,
};
return await axios.get(
`${baseUrl}/api/public/v1/config-values/all/shows/${summitId}`,
{ params }
)
.then(response => {
return response.data.data
})
.catch(e => console.log('ERROR: ', e));
};
const SSR_getEvents = async (baseUrl, summitId, accessToken, page = 1, results = []) => {
console.log(`SSR_getEvents page ${page} results ${results.length}`)
return await axios.get(
`${baseUrl}/api/v1/summits/${summitId}/events/published`,
{
params: {
access_token: accessToken,
per_page: 50,
page: page,
expand: 'slides, links, videos, media_uploads, type, track, track.allowed_access_levels, location, location.venue, location.floor, speakers, moderator, sponsors, current_attendance, groups, rsvp_template, tags',
}
}).then(({ data }) => {
console.log(`SSR_getEvents then data.current_page ${data.current_page} data.last_page ${data.last_page} total ${data.total}`)
if (data.current_page < data.last_page) {
return SSR_getEvents(baseUrl, summitId, accessToken, data.current_page + 1, [...results, ...data.data]);
}
return [...results, ...data.data];
})
.catch(e => console.log('ERROR: ', e));
};
const SSR_getSpeakers = async (baseUrl, summitId, accessToken, filter = null, page = 1, results = []) => {
console.log(`SSR_getSpeakers page ${page} results ${results.length}`)
const params = {
access_token: accessToken,
per_page: 30,
page: page,
};
if (filter) {
params['filter[]'] = filter;
}
return await axios.get(
`${baseUrl}/api/v1/summits/${summitId}/speakers/on-schedule`,
{ params }
)
.then(({ data }) => {
console.log(`SSR_getSpeakers then data.current_page ${data.current_page} data.last_page ${data.last_page} total ${data.total}`)
if (data.current_page < data.last_page) {
return SSR_getSpeakers(baseUrl, summitId, accessToken, filter, data.current_page + 1, [...results, ...data.data]);
}
return [...results, ...data.data];
})
.catch(e => console.log('ERROR: ', e));
};
const SSR_getSummit = async (baseUrl, summitId) => {
const params = {
expand: 'event_types,tracks,track_groups,presentation_levels,locations.rooms,locations.floors,order_extra_questions.values,schedule_settings,schedule_settings.filters,schedule_settings.pre_filters',
t: Date.now()
};
return await axios.get(
`${baseUrl}/api/public/v1/summits/${summitId}`,
{ params }
)
.then(({ data }) => data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getSummitExtraQuestions = async (baseUrl, summitId, accessToken) => {
let apiUrl = URI(`${baseUrl}/api/v1/summits/${summitId}/order-extra-questions`);
apiUrl.addQuery('filter[]', 'class==MainQuestion');
apiUrl.addQuery('filter[]', 'usage==Ticket');
apiUrl.addQuery('expand', '*sub_question_rules,*sub_question,*values')
apiUrl.addQuery('access_token', accessToken);
apiUrl.addQuery('order', 'order');
apiUrl.addQuery('page', 1);
apiUrl.addQuery('per_page', 100);
return await axios.get(apiUrl.toString())
.then(({data}) => data.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getVoteablePresentations = async (baseUrl, summitId, accessToken, page = 1, results = []) => {
console.log(`SSR_getVoteablePresentations page ${page} results ${results.length}`)
return await axios.get(
`${baseUrl}/api/v1/summits/${summitId}/presentations/voteable`,
{
params: {
access_token: accessToken,
per_page: 50,
page: page,
filter: 'published==1',
expand: 'slides, links, videos, media_uploads, type, track, track.allowed_access_levels, location, location.venue, location.floor, speakers, moderator, sponsors, current_attendance, groups, rsvp_template, tags',
}
}).then(({ data }) => {
console.log(`SSR_getVoteablePresentations then data.current_page ${data.current_page} data.last_page ${data.last_page} total ${data.total}`)
if (data.current_page < data.last_page) {
return SSR_getVoteablePresentations(baseUrl, summitId, accessToken, data.current_page + 1, [...results, ...data.data]);
}
return [...results, ...data.data];
})
.catch(e => console.log('ERROR: ', e));
};
exports.onPreBootstrap = async () => {
const summitId = process.env.GATSBY_SUMMIT_ID;
const summitApiBaseUrl = process.env.GATSBY_SUMMIT_API_BASE_URL;
const marketingData = await SSR_getMarketingSettings(process.env.GATSBY_MARKETING_API_BASE_URL, process.env.GATSBY_SUMMIT_ID);
const colorSettings = fs.existsSync(colorsFilepath) ? JSON.parse(fs.readFileSync(colorsFilepath)) : {};
const disqusSettings = fs.existsSync(disqusFilepath) ? JSON.parse(fs.readFileSync(disqusFilepath)) : {};
const marketingSite = fs.existsSync(marketingFilepath) ? JSON.parse(fs.readFileSync(marketingFilepath)) : {};
const homeSettings = fs.existsSync(homeFilepath) ? JSON.parse(fs.readFileSync(homeFilepath)) : {};
const globalSettings = fs.existsSync(settingsFilepath) ? JSON.parse(fs.readFileSync(settingsFilepath)) : {};
const config = {
client: {
id: process.env.GATSBY_OAUTH2_CLIENT_ID_BUILD,
secret: process.env.GATSBY_OAUTH2_CLIENT_SECRET_BUILD
},
auth: {
tokenHost: process.env.GATSBY_IDP_BASE_URL,
tokenPath: process.env.GATSBY_OAUTH_TOKEN_PATH
},
options: {
authorizationMethod: 'header'
}
};
const accessToken = await getAccessToken(config, process.env.GATSBY_BUILD_SCOPES).then(({ token }) => token.access_token);
// Marketing Settings
marketingData.map(({ key, value }) => {
if (key.startsWith('color_')) colorSettings[key] = value;
if (key.startsWith('disqus_')) disqusSettings[key] = value;
if (key.startsWith('summit_')) marketingSite[key] = value;
if (key === 'schedule_default_image') homeSettings.schedule_default_image = value;
if (key === 'registration_in_person_disclaimer') marketingSite[key] = value;
});
// Set the size property on marketing settings masonry if it's needed
const migrateMasonry = (masonry) => {
const sizeRequired = masonry.some(i => !i.hasOwnProperty("size"));
if (sizeRequired) {
return masonry.map((i) => {
isSingle = masonry.some(img => sizeOf(`./static${img.images[0].image}`).height > sizeOf(`./static${i.images[0].image}`).height);
return { ...i, size: isSingle ? 1: 2 }
})
}
return masonry;
}
Object.keys(marketingSite).map((key) => {
if (key === 'sponsors') marketingSite[key] = migrateMasonry(marketingSite[key]);
});
globalSettings.lastBuild = Date.now();
fs.writeFileSync(colorsFilepath, JSON.stringify(colorSettings), 'utf8');
fs.writeFileSync(disqusFilepath, JSON.stringify(disqusSettings), 'utf8');
fs.writeFileSync(marketingFilepath, JSON.stringify(marketingSite), 'utf8');
fs.writeFileSync(homeFilepath, JSON.stringify(homeSettings), 'utf8');
fs.writeFileSync(settingsFilepath, JSON.stringify(globalSettings), 'utf8');
let sassColors = '';
Object.entries(colorSettings).forEach(([key, value]) => sassColors += `$${key} : ${value};\n`);
fs.writeFileSync('src/styles/colors.scss', sassColors, 'utf8');
// Show Events
const allEvents = await SSR_getEvents(summitApiBaseUrl, summitId, accessToken);
console.log(`allEvents ${allEvents.length}`);
fs.writeFileSync('src/content/events.json', JSON.stringify(allEvents), 'utf8');
// Show Speakers
const allSpeakers = await SSR_getSpeakers(summitApiBaseUrl, summitId, accessToken);
console.log(`allSpeakers ${allSpeakers.length}`);
fs.writeFileSync('src/content/speakers.json', JSON.stringify(allSpeakers), 'utf8');
// Voteable Presentations
const allVoteablePresentations = await SSR_getVoteablePresentations(summitApiBaseUrl, summitId, accessToken);
console.log(`allVoteablePresentations ${allVoteablePresentations.length}`);
fs.writeFileSync('src/content/voteable_presentations.json', JSON.stringify(allVoteablePresentations), 'utf8');
// Get Summit Extra Questions
const extraQuestions = await SSR_getSummitExtraQuestions(summitApiBaseUrl, summitId, accessToken);
console.log(`extraQuestions ${extraQuestions.length}`);
fs.writeFileSync('src/content/extra-questions.json', JSON.stringify(extraQuestions), 'utf8');
};
// makes Summit logo optional for graphql queries
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type Summit implements Node {
logo: String
}
`;
createTypes(typeDefs)
};
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions;
/**
* Gatsby v4 Upgrade NOTE: This is no longer needed in `gatsby-remark-relative-images` v2.
* @see https://www.npmjs.com/package/gatsby-remark-relative-images#v2-breaking-changes
*/
// fmImagesToRelative(node); // convert image paths for gatsby images
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode });
createNodeField({
name: `slug`,
node,
value,
})
}
};
exports.sourceNodes = async ({
actions,
createNodeId,
createContentDigest
}) => {
const { createNode } = actions;
const summit = await SSR_getSummit(process.env.GATSBY_SUMMIT_API_BASE_URL, process.env.GATSBY_SUMMIT_ID);
const summitObject = { summit };
fs.writeFileSync('src/content/summit.json', JSON.stringify(summitObject), 'utf8');
const nodeContent = JSON.stringify(summit);
const nodeMeta = {
...summit,
id: createNodeId(`summit-${summit.id}`),
summit_id: summit.id,
parent: null,
children: [],
internal: {
type: `Summit`,
mediaType: `application/json`,
content: nodeContent,
contentDigest: createContentDigest(summit)
}
};
const node = Object.assign({}, summit, nodeMeta);
createNode(node)
};
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions;
return graphql(`
{
allMarkdownRemark(limit: 1000) {
edges {
node {
id
fields {
slug
}
frontmatter {
templateKey
}
}
}
}
}
`).then((result) => {
if (result.errors) {
result.errors.forEach((e) => console.error(e.toString()));
return Promise.reject(result.errors)
}
const posts = result.data.allMarkdownRemark.edges;
posts.forEach((edge) => {
const id = edge.node.id;
if (edge.node.fields.slug.match(/custom-pages/)) {
edge.node.fields.slug = edge.node.fields.slug.replace('/custom-pages/', '/');
}
createPage({
path: edge.node.fields.slug,
component: path.resolve(
`src/templates/${String(edge.node.frontmatter.templateKey)}.js`
),
// additional data can be passed via context
context: {
id,
},
})
})
})
};
exports.onCreateWebpackConfig = ({ actions, plugins, loaders }) => {
actions.setWebpackConfig({
resolve: {
/**
* Webpack removed automatic polyfills for these node APIs in v5,
* so we need to patch them in the browser.
* @see https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v2-to-v3/#webpack-5-node-configuration-changed-nodefs-nodepath-
* @see https://viglucci.io/how-to-polyfill-buffer-with-webpack-5
*/
fallback: {
path: require.resolve('path-browserify'),
stream: require.resolve('stream-browserify'),
buffer: require.resolve('buffer/')
}
},
// canvas is a jsdom external dependency
externals: ['canvas'],
plugins: [
plugins.define({
'global.GENTLY': false,
'global.BLOB': false
}),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
]
})
};