-
Notifications
You must be signed in to change notification settings - Fork 10
/
gatsby-node.js
567 lines (523 loc) · 15.2 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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
const crypto = require('crypto');
const path = require('path');
const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
const WebpackAssetsManifest = require('webpack-assets-manifest');
const chinaHelper = require('./src/helpers/chinaHelper');
const { SkillSort } = require('./src/helpers/skillSort');
const { getViewDataFromCRM, getUsersSkills } = require('./src/helpers/CRMApi');
const appInsights = require('applicationinsights');
const fs = require('fs');
const siteconfig = require('./site-config');
const matter = require('gray-matter');
const environment = process.env.NODE_ENV;
const appInsightsConnectionString =
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING;
if (!appInsightsConnectionString) {
// eslint-disable-next-line no-console
console.warn(
'Missing APPLICATIONINSIGHTS_CONNECTION_STRING, this build will not be logged to Application Insights'
);
} else if (environment === 'development') {
/* eslint-disable no-console */
console.info('Application Insights is disabled in development mode');
} else {
// Log build time stats to appInsights
const config = appInsights
.setup(appInsightsConnectionString)
.setAutoCollectConsole(true, true); // Enable logging of console.xxx
const client = appInsights.defaultClient;
// Add a telemetry initializer if needed
client.addTelemetryProcessor((envelope) => {
envelope.tags[appInsights.defaultClient.context.keys.cloudRole] =
'GatsbyBuildProcess';
});
config.start();
}
let assetsManifest = {};
const alumniPrefix = siteconfig.alumniPrefix;
const profileChineseTag = '-Chinese';
exports.onCreateWebpackConfig = ({ stage, loaders, getConfig, actions }) => {
const config = getConfig();
//Fix thrid party module needing window as per https://www.gatsbyjs.com/docs/debugging-html-builds/#fixing-third-party-modules
if (stage === 'build-html') {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-lazy-youtube/,
use: loaders.null(),
},
],
},
resolve: {
alias: {
path: require.resolve('path-browserify'),
},
fallback: {
fs: false,
},
},
});
}
if (stage.startsWith('develop') && config.resolve) {
config.resolve.alias = {
...config.resolve.alias,
};
}
actions.setWebpackConfig({
plugins: [
new WebpackAssetsManifest({
assets: assetsManifest, // mutates object with entries
merge: true,
}),
],
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
fallback: {
fs: false,
stream: require.resolve('stream-browserify'),
buffer: require.resolve('buffer/'),
util: require.resolve('util/'),
assert: require.resolve('assert/'),
http: require.resolve('stream-http/'),
url: require.resolve('url/'),
https: require.resolve('https-browserify/'),
os: require.resolve('os-browserify/'),
zlib: require.resolve('browserify-zlib'),
},
plugins: [
new DirectoryNamedWebpackPlugin({
exclude: /node_modules/,
}),
],
},
});
};
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type SitePage implements Node @dontInfer {
path: String!
}
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
id: String
name: String
qualifications: String
quote: String
quoteAuthor: String
role: String
jobTitle: String
alternativeUrl: String
}
`;
createTypes(typeDefs);
};
const loadSampleData = (crmData) => {
try {
let rawdata = fs.readFileSync('SampleProfileCRMData.json');
let sampleData = JSON.parse(rawdata);
sampleData.forEach((user) => {
if (user.userId) {
crmData.push(user);
}
});
} catch {
// if error, then we don't add anything
}
};
exports.sourceNodes = async ({
actions,
createNodeId,
createContentDigest,
}) => {
const { createNode } = actions;
{
const res = await fetch('https://www.ssw.com.au/api/get-megamenu');
const menuData = await res.json();
menuData?.menuGroups.forEach((group) => {
const node = {
id: createNodeId(`megamenugroup-${group.name}`),
parent: null,
children: [],
internal: {
type: 'MegaMenuGroup',
contentDigest: createContentDigest(group),
},
...group,
};
createNode(node);
});
}
const crmDataResult = await getViewDataFromCRM();
let skills = await getUsersSkills();
skills = skills
.map((user) => {
return {
service: user.technology,
marketingPage: user.marketingPage,
marketingPageUrl: user.marketingPageUrl,
highlightskill: user.highlightskill,
};
})
.filter(
(value, index, self) =>
index === self.findIndex((t) => t.service === value.service)
);
// load data for the sample profile
loadSampleData(crmDataResult);
crmDataResult.map((user) => {
const userNode = {
id: user.userId,
parent: '__SOURCE__',
internal: {
type: 'CrmDataCollection',
},
children: [],
slug: user.fullName
? user.fullName.replace(' ', '-')
: `${user.firstName}-${user.lastName}`,
fullName: user.fullName
? user.fullName
: `${user.firstName} ${user.lastName}`,
emailAddress: user.emailAddress || '',
location: user.defaultSite ? user.defaultSite : 'Others',
jobTitle: user.jobTitle.replace(/(SSW)(?! TV)/g, '') || '',
role: user.role || '',
billingRate: user.billableRate || '',
skills: {
intermediateSkills: user.skills
.filter((s) => s.experienceLevel === 'Intermediate')
.sort(SkillSort)
.map((s) => {
return {
service: s.technology,
marketingPageUrl: s.marketingPageUrl,
};
}),
advancedSkills: user.skills
.filter((s) => s.experienceLevel === 'Advanced')
.sort(SkillSort)
.map((s) => {
return {
service: s.technology,
marketingPageUrl: s.marketingPageUrl,
};
}),
},
isActive: user.isActive,
nickname: user.nickname || '',
blogUrl: user.blogUrl || '',
facebookUrl: user.facebookUrl || '',
skypeUsername: user.skypeUsername || '',
linkedInUrl: user.linkedInUrl || '',
twitterUsername: user.twitterUsername || '',
gitHubUrl: user.gitHubUrl || '',
youTubePlayListId: user.youTubePlayListId || '',
publicPhotoAlbumUrl: user.publicPhotoAlbumUrl || '',
};
// Get content digest of node. (Required field)
const contentDigest = crypto
.createHash('md5')
.update(JSON.stringify(userNode))
.digest('hex');
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
skills.map((service) => {
createNode({
service,
id: createNodeId(service.service),
internal: {
type: 'SkillUrls',
contentDigest: createContentDigest(service),
},
});
});
};
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allSkillUrls {
nodes {
id
service {
service
marketingPage
marketingPageUrl
highlightskill
}
}
}
people: allMarkdownRemark {
nodes {
parent {
... on File {
name
}
}
frontmatter {
id
name
qualifications
quote
quoteAuthor
role
jobTitle
}
html
rawMarkdownBody
}
}
peopleCRM: allCrmDataCollection {
nodes {
id
isActive
nickname
skills {
advancedSkills {
service
marketingPageUrl
}
intermediateSkills {
service
marketingPageUrl
}
}
location
jobTitle
billingRate
role
emailAddress
skypeUsername
twitterUsername
gitHubUrl
youTubePlayListId
blogUrl
facebookUrl
linkedInUrl
fullName
publicPhotoAlbumUrl
}
}
peopleAudios: allFile(
filter: {
sourceInstanceName: { eq: "people" }
name: { glob: "*-Audio" }
}
) {
nodes {
name
publicURL
}
}
peopleProfileImages: allFile(
filter: {
sourceInstanceName: { eq: "people" }
name: { glob: "*-Profile" }
}
) {
nodes {
childImageSharp {
original {
src
}
parent {
... on File {
name
}
}
}
}
}
peopleSketchImages: allFile(
filter: {
sourceInstanceName: { eq: "people" }
name: { glob: "*-Sketch" }
}
) {
nodes {
childImageSharp {
original {
src
}
parent {
... on File {
name
}
}
}
}
}
}
`);
const skillUrls = data.allSkillUrls.nodes.map((node) => {
return node;
});
const peopleCRM = data.peopleCRM.nodes.map((node) => {
return node;
});
const peopleAudios = data.peopleAudios.nodes.map((node) => {
return {
src: node.publicURL,
name: node.name.replace('-Audio', ''),
};
});
const peopleProfileImages = data.peopleProfileImages.nodes.map((node) => {
return {
src: node.childImageSharp.original.src,
name: node.childImageSharp.parent.name.replace('-Profile', ''),
};
});
const peopleSketchImages = data.peopleSketchImages.nodes.map((node) => {
return {
src: node.childImageSharp.original.src,
name: node.childImageSharp.parent.name.replace('-Sketch', ''),
};
});
const people = data.people.nodes
.filter(
(node) =>
node.frontmatter.id &&
(peopleCRM.find((x) => x.id === node.frontmatter.id) ||
node.frontmatter.id.indexOf('-') < 0)
)
.map((node) => {
const crmData = peopleCRM.find((x) => x.id === node.frontmatter.id);
const isCurrent = crmData ? crmData.isActive : false;
const nickname = crmData ? crmData.nickname : null;
const prefix = isCurrent ? '' : alumniPrefix.replace('/', '') + '/';
return {
slug: node.parent.name,
path: prefix + node.parent.name.toLowerCase(),
nicknamePath: nickname
? prefix + nickname.replace(/ /g, '-').toLowerCase()
: '',
frontmatter: node.frontmatter,
dataCRM: crmData,
dataSkillUrls: skillUrls,
audio: peopleAudios.find(
(x) => x.name === node.parent.name.replace(profileChineseTag, '')
),
profileImage: peopleProfileImages.find(
(x) => x.name === node.parent.name.replace(profileChineseTag, '')
),
sketchImage: peopleSketchImages.find(
(x) => x.name === node.parent.name.replace(profileChineseTag, '')
),
html: node.html,
rawMarkdown: node.rawMarkdownBody,
};
});
const peoplePath = './public';
if (!fs.existsSync(peoplePath)) {
fs.mkdirSync(peoplePath);
}
const peopleList = people
.filter((person) => !person.path.includes('alumni'))
.map((person) => person.path);
fs.writeFileSync(`${peoplePath}/people.json`, JSON.stringify(peopleList));
people.forEach((person) => {
/* eslint-disable no-console */
console.log('Creating page for ' + person.slug);
console.log('\tPath: ' + person.path);
console.log('\tNickname: ' + person.nicknamePath);
/* eslint-enable no-console */
actions.createPage({
path: person.path,
component: require.resolve('./src/templates/person.js'),
context: {
slug: person.slug,
originalPath: person.path,
nicknamePath: person.nicknamePath,
data: {
audio: person.audio,
profileImage: person.profileImage,
sketchImage: person.sketchImage,
frontmatter: person.frontmatter,
dataCRM: person.dataCRM,
dataSkillUrls: person.dataSkillUrls,
html: chinaHelper.isChinaBuild
? chinaHelper.cleanHtml(person.html)
: person.html,
},
},
});
function getLastSegment(url) {
const segments = url.split('/');
return segments[segments.length - 1];
}
// if person has a nickname (even if they are alumni), create a redirect from it
if (person.nicknamePath && person.path !== person.nicknamePath) {
const nicknamePath = person.nicknamePath.replace(
alumniPrefix.replace('/', ''),
''
);
actions.createRedirect({
fromPath: nicknamePath,
toPath: `/${person.path}`,
isPermanent: true,
});
/* eslint-disable no-console */
console.log(
'Creating redirect from ' + nicknamePath + ' to ' + person.path
);
}
if (person.path.includes('alumni')) {
const originalPath = getLastSegment(person.path); // Gets the path, removing the /alumni/ prefix
actions.createRedirect({
fromPath: originalPath,
toPath: `/${person.path}`, // Redirects to the alumni page
isPermanent: true,
});
return;
}
const filePath = `./public/${person.path}`;
if (!fs.existsSync(filePath)) {
fs.mkdirSync(filePath);
}
const skills = [];
skills.push(
...person.dataCRM.skills.intermediateSkills.map((skill) => skill.service)
);
skills.push(
...person.dataCRM.skills.advancedSkills.map((skill) => skill.service)
);
const sanitisedMarkdown = (input) => {
const lines = input.split('\n');
const filteredLines = lines.filter((line) => {
const imgRegex = /!\[.*\](.*)/;
const emptyLineRegex = /^\s*$/; // this gets rid of '\r' lines
return (
!imgRegex.test(line) &&
!line.trim().includes('[[imgBadge]]') &&
!line.trim().includes('[Editing profiles]') &&
!line.trim().includes('<br/>') &&
!line.trim().includes('---') &&
!line.trim().startsWith('#') &&
!emptyLineRegex.test(line) &&
line.length !== 0
);
});
var output = filteredLines.join('\n');
return output.split('\n', 2).join('\n');
};
var profileData = {
skills: skills.join(' | '),
position: person.dataCRM.jobTitle.trim(),
presenter: {
name: person.dataCRM.fullName,
peopleProfileURL: 'https://www.ssw.com.au/people/' + person.path,
},
about: sanitisedMarkdown(person.rawMarkdown),
};
fs.writeFileSync(
`${filePath}/profile.md`,
matter.stringify('', profileData)
);
});
};