generated from nandiheath/gatsby-template-deprecated
-
Notifications
You must be signed in to change notification settings - Fork 43
/
gatsby-node.js
799 lines (765 loc) · 23.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/**
import publicLoader from './.cache/loader';
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const fetch = require("node-fetch")
const csv2json = require("csvtojson")
const path = require("path")
const ae = require("./ae")
const gn = require("./gn")
// const GOOGLE_SPREADSHEET_ID = "14kreo2vRo1XCUXqFLcMApVtYmvkEzWBDm6b8fzJNKEc"
const LANGUAGES = ["zh", "en"]
const { request } = require("graphql-request")
const { getPath, getWarTipPath } = require("./src/utils/urlHelper")
const isDebug = process.env.DEBUG_MODE === "true"
// const moment = require("moment")
const fs = require("fs")
const PUBLISHED_SPREADSHEET_I18N_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vRTVp8L95wLd23_2CuA57V-lU6tCRhGAPWSCghGhBuV4xKV_XMVjniCEoDxZnBMXEJ2MPlAi6WzOxlp/pub?gid=0"
const PUBLISHED_SPREADSHEET_WARS_CASES_URLS = [
"https://docs.google.com/spreadsheets/d/e/2PACX-1vSr2xYotDgnAq6bqm5Nkjq9voHBKzKNWH2zvTRx5LU0jnpccWykvEF8iB_0g7Tzo2pwzkTuM3ETlr_h/pub?gid=0",
"https://docs.google.com/spreadsheets/d/e/2PACX-1vT-Xw-QHYydz_kJCJLBqTKGbb2OF8_gisdUsduPbdR6Dp3tLbWxy_mkfRx2tMmGJ0q64uNsLLv3bbfb/pub?gid=0",
"https://docs.google.com/spreadsheets/d/e/2PACX-1vTEJyeLTOgntmUjeRhyEB1w_eFD6BUKAEgkR47pp3yXY_XB3IlF7DstsAA0pHz33h2pzGIxGbvGhjMe/pub?gid=0",
]
const PUBLISHED_SPREADSHEET_DODGY_SHOPS_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vT_CejomuSCl7198EZ7JgujiAfcxwao-4_X5d3V8VasBKGTvSVtfPrFCl3NGMEwo_a6wZbmKZcqV-sB/pub?gid=1018551822"
const PUBLISHED_SPREADSHEET_WARS_TIPS_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vR6Zri9Rt6egCzKgs2PBdyCpEECI338XZ3UwqJqfEpffW6tnlterGLRne8uS1EKy6tS_Ba4u5OKitmP/pub?gid=0"
const PUBLISHED_SPREADSHEET_DISRUPTION_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vS0gZ-QBC6JGMS28kYUMz90ZNXFb40CtoLtOIC-QzzlqhPKCIrAojuuN2GX6AXaECONvxJd84tpqzFd/pub?gid=0"
const PUBLISHED_SPREADSHEET_DISRUPTION_DESCRIPTION_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vS0gZ-QBC6JGMS28kYUMz90ZNXFb40CtoLtOIC-QzzlqhPKCIrAojuuN2GX6AXaECONvxJd84tpqzFd/pub?gid=268131605"
const PUBLISHED_SPREADSHEET_WARS_CASES_LOCATION_URLS = [
"https://docs.google.com/spreadsheets/d/e/2PACX-1vT6aoKk3iHmotqb5_iHggKc_3uAA901xVzwsllmNoOpGgRZ8VAA3TSxK6XreKzg_AUQXIkVX5rqb0Mo/pub?gid=0",
"https://docs.google.com/spreadsheets/d/e/2PACX-1vQVRg6iiYOHZwLsXdZE6TVWBO7Cldi07NUnbeVY3nI97_IjyG3jiWnjaUS51HRNJI1fN3io1paMa6jZ/pub?gid=0",
"https://docs.google.com/spreadsheets/d/e/2PACX-1vTl_YWJy_osrNeOD0ufyQH4CuWTKCX9ng-tUPpIFXsAdk_ry2uciIt752f9a-yd83IGUtsw2rHQNB0s/pub?gid=0",
]
const PUBLISHED_SPREADSHEET_BOT_WARS_LATEST_FIGURES_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vTiCndDnXu6l5ZKq2aAVgU2xM3WGGW68XF-pEbLAloRbOzA1QwglLGJ6gTKjFbLQGhbH6GR2TsJKrO7/pub?gid=0"
const PUBLISHED_OVERRIDE_MASTER_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vQc-XdUlx2VuIqZ71qze1Mg5m11OwA8wL5fYLdlU1VC1PcEqrRrKL6fL5_FbtihOtmeAi7t1puDXOvG/pub?gid=0"
const PUBLISHED_SPREADSHEET_FRIENDLY_LINK_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vRrwN4gNtogizNkYKGzMXpa7GTNJhE_vkZuYiFraU7f-N7ZKiT-araG-0jb586kczxc9Ua6oht8SVcE/pub?gid=0"
// const PUBLISHED_SPREADSHEET_WARS_CASES_LOCATION_599C_URL =
// "https://docs.google.com/spreadsheets/d/e/2PACX-1vQcfO-bjeNxNSJ2AFQdv-a855leMyzgO7Q7QXwgCGGmCAx7PwUxgrfcuJM8BLDCQL-nwnt123OZ4_mT/pub?gid=456240224"
const PUBLISHED_SPREADSHEET_TRAVEL_ALERT_URL =
"https://docs.google.com/spreadsheets/u/1/d/e/2PACX-1vQOnfZtGysW5qVe9FferSvhSODKa9ASH7SeqCGAGJSz8ZV7POm3kzFqfkbVAgryHKdj9WwLKXJai332/pub?gid=0"
const PUBLISHED_SPREADSHEET_IMPORTANT_INFORMATION_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vShepjZrGpn8QlN8R3QFrIVhWLg9l0F99wYR9khAnhmoydOP7hkS2_L1imCjH9nHkqVQf3xGrUAi8Na/pub?gid=257173560"
// const PUBLISHED_SPREADSHEET_SITE_CONFIG_URL =
// "https://docs.google.com/spreadsheets/d/e/2PACX-1vRUN7eL0XjPbkcmxnWKPH9_AOiRiIVcH25nLkOgbfRN7y1gk9tBucufIcLWTFFjjgMJNQmOxIFeU_Sk/pub?gid=0"
const PUBLISHED_SPREADSHEET_WARS_CASES_RELATIONSHIP_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vQS7Aay-dZbemZAxbW1oVrC5QKnT9wPjd55hSGGnXGj8_jdZJa9dsKYI--dTv4EU--xt_HGIDZsdNEw/pub?gid=0"
const PUBLISHED_SPREADSHEET_ALERT_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vRWN6o99FDJN4KsnAyq9KeWKEerF2_v1Z0wWbKiHPI0_Whuf00ZLW2n-GfoXciKgVXkBSoBEz6IhreC/pub?gid=0"
const PUBLISHED_SPREADSHEET_UPDATES_URL =
"https://docs.google.com/spreadsheets/d/e/2PACX-1vRY5OHr2hX8Xl_tJR1BgrffhoiVxqjngCu9W262MgyW5ZCXuZFaj1Od0PQJqNeRJ7ocUacI2WnodeTT/pub?gid=257173560"
const GRAPHQL_URL = "https://api2.vote4.hk/v1/graphql"
const createIMMDNode = async ({
actions: { createNode },
createNodeId,
createContentDigest,
}) => {
const type = "Immd"
const addNodeByGate = async gate => {
const query = `{
wars_immd(order_by: {date: desc}, limit: 2, where: {location: {_eq: "${gate}"}}) {
arrival_hong_kong
arrival_mainland
arrival_other
arrival_total
date
departure_hong_kong
departure_mainland
departure_other
departure_total
location
}
}`
const data = await request(GRAPHQL_URL, query)
data.wars_immd.forEach((p, i) => {
const gateKey = gate.replace(/[- ]/g, "")
const meta = {
id: createNodeId(`${type}${gateKey}-${i}`),
parent: null,
children: [],
internal: {
type: `${type}${gateKey}`,
contentDigest: createContentDigest(p),
},
}
const node = Object.assign({}, p, meta)
createNode(node)
})
}
addNodeByGate("Airport")
addNodeByGate("Hong Kong-Zhuhai-Macao Bridge")
addNodeByGate("Shenzhen Bay")
addNodeByGate("Total")
}
// const createWorldCasesNode = async ({
// actions: { createNode },
// createNodeId,
// createContentDigest,
// }) => {
// const lastWeek = moment()
// .add(-15, "days") // temp fix as we lost some baidu data
// .format("YYYY-MM-DD")
// const type = "BaiduInternationalData"
// const query = `{
// wars_BaiduInternationalData (
// where: {
// date: {
// _gt: "${lastWeek}"
// }
// }
// distinct_on: [date, area]
// order_by: [
// {date: desc},
// {area: desc},
// {time: desc},
// ]
// ) {
// area
// date
// time
// confirmed
// died
// crued
// }
// }`
// const baiduChinaQuery = `{
// wars_BaiduChinaData (
// where: {
// date: {
// _gt: "${lastWeek}"
// }
// }
// distinct_on: [date, area, city]
// order_by: [
// {date: desc},
// {area: desc},
// {city: desc},
// {time: desc},
// ]
// ) {
// area
// city
// date
// time
// confirmed
// died
// crued
// }
// }`
// const data = await request(GRAPHQL_URL, query)
// const baiduChinaData = await request(GRAPHQL_URL, baiduChinaQuery)
// data.wars_BaiduInternationalData.forEach((p, i) => {
// const meta = {
// id: createNodeId(`${type}-${i}`),
// parent: null,
// children: [],
// internal: {
// type,
// contentDigest: createContentDigest(p),
// },
// }
// const node = Object.assign({}, p, meta)
// createNode(node)
// })
// let count = data.wars_BaiduInternationalData.length
// let chinaCured = {}
// let chinaDied = {}
// let chinaConfirmed = {}
// let availableDate = []
// let dateTimeMapping = {}
// baiduChinaData.wars_BaiduChinaData.forEach(p => {
// if (
// p.area === "香港" ||
// p.area === "颱灣" ||
// p.area === "台灣" ||
// p.area === "澳門"
// ) {
// const node_data = {
// area: p.area === "颱灣" ? "台灣" : p.area,
// date: p.date,
// time: p.time,
// confirmed: p.confirmed,
// died: p.died,
// crued: p.crued,
// }
// const meta = {
// id: createNodeId(`${type}-${count}`),
// parent: null,
// children: [],
// internal: {
// type,
// contentDigest: createContentDigest(node_data),
// },
// }
// const node = Object.assign({}, node_data, meta)
// createNode(node)
// count += 1
// } else if (p.city === "") {
// if (availableDate.includes(p.date)) {
// chinaCured[p.date] += p.crued
// chinaDied[p.date] += p.died
// chinaConfirmed[p.date] += p.confirmed
// } else {
// availableDate.push(p.date)
// dateTimeMapping[p.date] = p.time
// chinaCured[p.date] = p.crued
// chinaDied[p.date] = p.died
// chinaConfirmed[p.date] = p.confirmed
// }
// }
// })
// availableDate.forEach(date => {
// const node_data = {
// area: "中国",
// date: date,
// time: dateTimeMapping[date],
// confirmed: chinaConfirmed[date],
// died: chinaDied[date],
// crued: chinaCured[date],
// }
// const meta = {
// id: createNodeId(`${type}-${count}`),
// parent: null,
// children: [],
// internal: {
// type,
// contentDigest: createContentDigest(node_data),
// },
// }
// const node = Object.assign({}, node_data, meta)
// createNode(node)
// count += 1
// })
// }
const createAENode = async ({
actions: { createNode },
createNodeId,
createContentDigest,
}) => {
const type = "AEWaitingTime"
const output = await ae.fetchAEWaitingTime()
const { records } = output
records.forEach((p, i) => {
const meta = {
id: createNodeId(`${type.toLowerCase()}-${i}`),
parent: null,
children: [],
internal: {
type,
contentDigest: createContentDigest(p),
},
}
const node = Object.assign({}, p, meta)
createNode(node)
})
}
const createGovNewsNode = async ({
actions: { createNode, createTypes },
createNodeId,
createContentDigest,
}) => {
const type = "GovNews"
const output = await gn.fetchGovNews()
const { records } = output
const typeTemplate = `
type ${type} implements Node {
title_en: String
title_zh: String
link_en: String
link_zh: String
date: String
}
`
createTypes(typeTemplate)
records.forEach((p, i) => {
const meta = {
id: createNodeId(`${type.toLowerCase()}-${i}`),
parent: null,
children: [],
internal: {
type,
contentDigest: createContentDigest(p),
},
}
const node = Object.assign({}, p, meta)
createNode(node)
})
}
// const createNode = async (
// { actions: { createNode }, createNodeId, createContentDigest },
// sheetName,
// type
// ) => {
// // All table has first row reserved
// const result = await fetch(
// `https://docs.google.com/spreadsheets/d/${GOOGLE_SPREADSHEET_ID}/gviz/tq?tqx=out:csv&sheet=${sheetName}&range=A2:ZZ&headers=0`
// )
// const data = await result.text()
// const records = await csv2json().fromString(data)
// records.forEach((p, i) => {
// // create node for build time data example in the docs
// const meta = {
// // required fields
// id: createNodeId(`${type.toLowerCase()}-${i}`),
// parent: null,
// children: [],
// internal: {
// type,
// contentDigest: createContentDigest(p),
// },
// }
// const node = Object.assign({}, p, meta)
// createNode(node)
// })
// }
const createPublishedGoogleSpreadsheetNode = async (
{ actions: { createNode, createTypes }, createNodeId, createContentDigest },
publishedURLs,
type,
{ skipFirstLine = false, alwaysEnabled = false, subtype = null }
) => {
// All table has first row reserved
let urls = publishedURLs
if (typeof publishedURLs === "string") {
urls = [publishedURLs]
}
const requests = urls.map(url => {
return fetch(
`${url}&single=true&output=csv&headers=0${
skipFirstLine ? "&range=A2:ZZ" : ""
}&q=${Math.floor(new Date().getTime(), 1000)}`
)
.then(result => result.text())
.then(data => csv2json().fromString(data))
})
// flatten the records from returning value of multiple requests
const records = (await Promise.all(requests)).flat()
const filteredRecords = records.filter(
r => alwaysEnabled || (isDebug && r.enabled === "N") || r.enabled === "Y"
)
if (filteredRecords.length > 0) {
filteredRecords.forEach((p, i) => {
// create node for build time data example in the docs
const meta = {
// required fields
id: createNodeId(
`${type.toLowerCase()}${subtype ? `-${subtype}` : ""}-${i}`
),
parent: null,
children: [],
internal: {
type,
contentDigest: createContentDigest(p),
},
}
const node = { ...p, subtype, ...meta }
createNode(node)
})
} else if (records.length > 0) {
// So if filtered rows is empty,
// we manually create the type here.
// TODO: handle not even a single row ...
const fields = Object.keys(records[0])
const fieldString = fields.map(field => `${field}: String`).join("\n")
const typeTemplate = `
type ${type} implements Node {
${fieldString}
}
`
createTypes(typeTemplate)
}
}
/*
=============== Gatsby API starts =================
*/
exports.onCreatePage = async ({ page, actions }) => {
const { createPage, deletePage } = actions
return new Promise(resolve => {
// If it is already eng path we skip to re-generate the locale
if (!page.path.match(/^\/en/)) {
deletePage(page)
LANGUAGES.forEach(lang => {
const path = getPath(lang, page.path)
createPage({
...page,
matchPath: page.path.includes("cases")
? (path + "/*").replace(/[/]+\*/, "/*")
: page.matchPath,
path,
context: {
...page.context,
locale: lang,
},
})
})
}
resolve()
})
}
exports.onCreateWebpackConfig = ({ stage, loaders, actions, getConfig }) => {
if (stage === "build-html") {
const regex = [
/node_modules\/leaflet/,
/node_modules\\leaflet/,
/node_modules\/pixi.js/,
/node_modules\\pixi.js/,
]
actions.setWebpackConfig({
module: {
rules: [
{
test: regex,
use: loaders.null(),
},
],
},
})
}
if (getConfig().mode === "production") {
actions.setWebpackConfig({
devtool: false,
})
}
}
exports.sourceNodes = async props => {
await Promise.all([
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_I18N_URL,
"i18n",
{ skipFirstLine: false, alwaysEnabled: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_WARS_CASES_URLS,
"WarsCase",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_WARS_CASES_LOCATION_URLS,
"WarsCaseLocation",
{
skipFirstLine: true,
subtype: "default",
}
),
// createPublishedGoogleSpreadsheetNode(
// props,
// PUBLISHED_SPREADSHEET_WARS_CASES_LOCATION_599C_URL,
// "WarsCaseLocation",
// {
// skipFirstLine: true,
// subtype: "599c",
// }
// ),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_DODGY_SHOPS_URL,
"DodgyShop",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_WARS_TIPS_URL,
"WarsTip",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_DISRUPTION_URL,
"Disruption",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_DISRUPTION_DESCRIPTION_URL,
"DisruptionDescription",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_BOT_WARS_LATEST_FIGURES_URL,
"BotWarsLatestFigures",
{ skipFirstLine: true, alwaysEnabled: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_OVERRIDE_MASTER_URL,
"WarsLatestFiguresOverride",
{ skipFirstLine: true, alwaysEnabled: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_FRIENDLY_LINK_URL,
"FriendlyLink",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_TRAVEL_ALERT_URL,
"BorderShutdown",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_ALERT_URL,
"Alert",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_IMPORTANT_INFORMATION_URL,
"ImportantInformation",
{ skipFirstLine: true }
),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_UPDATES_URL,
"Updates",
{ skipFirstLine: true }
),
// createPublishedGoogleSpreadsheetNode(
// props,
// PUBLISHED_SPREADSHEET_SITE_CONFIG_URL,
// "SiteConfig",
// { skipFirstLine: true }
// ),
createPublishedGoogleSpreadsheetNode(
props,
PUBLISHED_SPREADSHEET_WARS_CASES_RELATIONSHIP_URL,
"WarsCaseRelation",
{ skipFirstLine: true }
),
createAENode(props),
createIMMDNode(props),
createGovNewsNode(props),
// createWorldCasesNode(props),
])
}
// https://www.gatsbyjs.org/docs/schema-customization/#foreign-key-fields
exports.createSchemaCustomization = ({ actions, schema }) => {
const { createTypes } = actions
const typeDefs = [
`type WarsCase implements Node {
locations: [WarsCaseLocation] @link(by: "case_no", from: "case_no") # easy back-ref
}`,
`type WarsCaseLocation implements Node {
case: WarsCase @link(by: "case_no", from: "case_no")
}`,
]
createTypes(typeDefs)
}
exports.createPages = async ({ graphql, actions }) => {
actions.createRedirect({
fromPath: `/hygiene-tips`,
toPath: `/wars-tips`,
redirectInBrowser: false,
isPermanent: true,
})
const result = await graphql(`
query {
allI18N {
edges {
node {
key
en
zh
}
}
}
allWarsTip {
edges {
node {
title
text
date
image_url
source_description
source_url
tags
language
}
}
}
allWarsCase {
edges {
node {
case_no
onset_date
confirmation_date
gender
age
hospital_zh
hospital_en
status
status_zh
status_en
type_zh
type_en
citizenship_zh
citizenship_en
detail_zh
detail_en
classification
classification_zh
classification_en
source_url_1
source_url_2
source_url_3
source_url_4
source_url_5
}
}
}
allWarsCaseRelation {
edges {
node {
case_no
name_zh
name_en
description_zh
description_en
}
}
}
patientTrack: allWarsCaseLocation(
sort: { order: DESC, fields: end_date }
) {
group(field: case___case_no) {
fieldValue
edges {
node {
case_no
start_date
end_date
sub_district_zh
sub_district_en
location_zh
location_en
action_zh
action_en
remarks_zh
remarks_en
source_url_1
source_url_2
}
}
}
}
}
`)
// Generate i18n translation json file
const translations = {
zh: {},
en: {},
}
result.data.allI18N.edges.forEach(edge => {
const {
node: { key, en, zh },
} = edge
translations["zh"][key] = zh
translations["en"][key] = en
})
LANGUAGES.forEach(lang => {
fs.mkdirSync(`src/locales/${lang}`, { recursive: true })
fs.writeFileSync(
`src/locales/${lang}/translation.json`,
JSON.stringify(translations[lang])
)
})
result.data.allWarsTip.edges.forEach(({ node }) => {
// This will not trigger onCreatePage
LANGUAGES.forEach(lang => {
const uri = getWarTipPath(lang, node.title)
if (node.language !== lang) {
// actions.createRedirect not working here.. dont know why
// so create a client side redirect here
actions.createPage({
path: uri,
component: path.resolve(`./src/templates/redirect.js`),
context: {
uri,
redirectURL: getPath(lang, "/wars-tips/"),
locale: lang,
},
})
} else {
actions.createPage({
path: uri,
component: path.resolve(`./src/templates/wars-tip.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
node,
locale: lang,
uri,
},
})
}
})
})
const groupArray = []
result.data.allWarsCaseRelation.edges.forEach(({ node }, id) => {
node.id = id + 1
node.case_no.split(",").forEach(nodeCase => {
groupArray.push({
...node,
related_cases: node.case_no,
case_no: parseInt(nodeCase),
})
})
})
return Promise.resolve(null)
}
exports.onPostBuild = async ({ graphql, reporter }) => {
reporter.info("Injecting cases pages sitemap record")
const fs = require("fs")
const result = await graphql(`
query {
allWarsCase {
edges {
node {
case_no
}
}
}
}
`)
const template = no =>
`<url> <loc>https://wars.vote4.hk/cases/${no}</loc> <changefreq>daily</changefreq> <priority>0.7</priority> </url>
<url> <loc>https://wars.vote4.hk/en/cases/${no}</loc> <changefreq>daily</changefreq> <priority>0.7</priority> </url>`
const caseNos = result.data.allWarsCase.edges.map(i => i.node.case_no)
const sitemapXml = fs.readFileSync("./public/sitemap.xml", "utf-8")
const caseNoSitemap = caseNos.map(template).join("\n")
fs.writeFileSync(
"./public/sitemap.xml",
sitemapXml.replace("</urlset>", caseNoSitemap + "\n</urlset>")
)
reporter.info("Setup cases routes and symlink for github SPA fallback")
for (const case_no of caseNos) {
try {
if (!fs.existsSync(`./public/cases/${case_no}`))
fs.mkdirSync(`./public/cases/${case_no}`)
if (!fs.existsSync(`./public/cases/${case_no}/index.html`))
fs.symlinkSync("../index.html", `./public/cases/${case_no}/index.html`)
if (!fs.existsSync(`./public/en/cases/${case_no}`))
fs.mkdirSync(`./public/en/cases/${case_no}`)
if (!fs.existsSync(`./public/en/cases/${case_no}/index.html`))
fs.symlinkSync(
"../index.html",
`./public/en/cases/${case_no}/index.html`
)
} catch (error) {
console.error(error)
}
}
}