-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgatsby-node.js
More file actions
1075 lines (976 loc) · 33.5 KB
/
gatsby-node.js
File metadata and controls
1075 lines (976 loc) · 33.5 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
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path')
const _ = require('lodash')
const fs = require("fs")
const webpack = require('webpack');
const axios = require('axios')
const {createFilePath} = require('gatsby-source-filesystem')
const {fmImagesToRelative} = require('gatsby-remark-relative-images')
const {ClientCredentials} = require('simple-oauth2');
const yaml = require("yaml")
const moment = require("moment-timezone");
const prevElectionsBasePath = 'src/pages/election/previous-elections';
const URI = require("urijs");
const { getPageSlugFromSEO } = require('./src/utils/methods');
const myEnv = require("dotenv").config({
path: `.env`,
expand: true
});
const currentYear = new Date().getFullYear();
const electionsSinceYear = process.env.GATSBY_ELECTION_SINCE_YEAR || 2023;
const minimunElectionsToShow = process.env.GATSBY_ELECTION_TO_SHOW || 2;
const electionsToShow = (currentYear - electionsSinceYear) + minimunElectionsToShow;
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 writeToJson = (filePath, data) => {
fs.writeFileSync(filePath, JSON.stringify(data), 'utf8', function (err) {
if (err) throw err;
console.log(`wrote ${filePath}`);
});
};
const SSR_getLegals = async (baseUrl) => {
return await axios.get(
`${process.env.GATSBY_API_BASE_URL}/api/public/v1/legal-documents/422`,
{}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getCurrentReleaseComponents = async (baseUrl) => {
return await axios.get(
`${baseUrl}/api/public/v1/releases/current`,
{
params: {
expand: 'components, components.component'
}
}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getSponsorshipTypes = async (baseUrl, sponsoredProjectId) => {
return await axios.get(
`${baseUrl}/api/public/v1/sponsored-projects/${sponsoredProjectId}/sponsorship-types`,
{
params: {
expand: 'supporting_companies, supporting_companies.company',
page: 1,
per_page: 100,
}
}).then((response) => response.data.data)
.catch(e => console.log('ERROR: ', e));
}
const SSR_getSponsoredProjects = async (baseUrl) => {
return await axios.get(
`${baseUrl}/api/public/v1/sponsored-projects/`,
{
params: {
per_page: 100,
page: 1,
expand: 'subprojects,subprojects.sponsorship_types,subprojects.sponsorship_types.supporting_companies,subprojects.sponsorship_types.supporting_companies.company'
}
}).then((response) => response.data.data)
.catch(e => console.log('ERROR: ', e));
}
const SSR_getPreviousElections = async (baseUrl, accessToken, page = 1) => {
const currentDate = parseInt(Date.now()/1000);
// minimun per page is 5
const perPage = electionsToShow > 5 ? electionsToShow : 5;
const url = `${baseUrl}/api/v1/elections/`;
console.log(`SSR_getPreviousElections url ${url} accessToken ${accessToken} currentDate ${currentDate} perPage ${perPage}`);
return await axios.get(
url,
{
params: {
access_token: accessToken,
page: page,
per_page: perPage,
filter: `closes<${currentDate}`,
order: '-closes'
}
}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getCurrentElection = async (baseUrl, accessToken, page = 1, perPage = 5) => {
return await axios.get(
`${baseUrl}/api/v1/elections/`,
{
params: {
access_token: accessToken,
page: page,
per_page: perPage,
order: '-closes'
}
}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getPreviousElectionCandidates = async (baseUrl, accessToken, electionId, page = 1) => {
return await axios.get(
`${baseUrl}/api/v1/elections/${electionId}/candidates/`,
{
params: {
access_token: accessToken,
per_page: 100,
page: page,
order: '+first_name,+last_name',
expand: 'member, member.election_applications, member.election_applications.nominator',
fields: 'member.election_applications.nominator.first_name, member.election_applications.nominator.last_name'
}
}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
const SSR_getPreviousElectionGoldCandidates = async (baseUrl, accessToken, electionId, page = 1) => {
return await axios.get(
`${baseUrl}/api/v1/elections/${electionId}/candidates/gold`,
{
params: {
access_token: accessToken,
per_page: 100,
page: page,
order: '+first_name,+last_name',
expand: 'member',
}
}).then((response) => response.data)
.catch(e => console.log('ERROR: ', e));
};
exports.onPreBootstrap = async () => {
const apiBaseUrl = process.env.GATSBY_API_BASE_URL;
const buildScopes = process.env.GATSBY_BUILD_SCOPES;
const sponsoredProjectId = process.env.GATSBY_SPONSORED_PROJECT_ID;
const globalSettings = {lastBuild: Date.now()};
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, buildScopes).then(({token}) => token.access_token).catch(e => console.log('Access Token error', e));
// settings
writeToJson('src/content/settings.json', globalSettings);
// pull legal doc
const legalDocument = await SSR_getLegals(apiBaseUrl);
if (legalDocument) {
writeToJson('src/content/legal-document.json', legalDocument);
}
// pull current release
const currentRelease = await SSR_getCurrentReleaseComponents(apiBaseUrl);
if (currentRelease) {
writeToJson('src/content/current-release.json', currentRelease);
}
// pull sponsorship types
const sponsorshipTypes = await SSR_getSponsorshipTypes(apiBaseUrl, sponsoredProjectId);
if (sponsorshipTypes) {
writeToJson('src/content/sponsorship-types.json', sponsorshipTypes);
}
// pull sponsored projects
const sponsoredProjects = await SSR_getSponsoredProjects(apiBaseUrl);
if (sponsoredProjects) {
writeToJson('src/content/sponsored-projects.json', sponsoredProjects);
}
}
exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
const { createNode } = actions;
const apiBaseUrl = process.env.GATSBY_API_BASE_URL;
const buildScopes = process.env.GATSBY_BUILD_SCOPES;
console.log(`onSourceNodes...`);
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, buildScopes).then(({token}) => token.access_token).catch(e => console.log('Access Token error', e));
// data for current election
const currentElection = await SSR_getCurrentElection(apiBaseUrl, accessToken).then((res) => res.data[0]);
createNode({
...currentElection,
id: `${currentElection.id}`,
electionYear: moment(currentElection.closes * 1000).utc().format('YYYY'),
parent: null,
children: [],
internal: {
type: 'CurrentElectionData', // Replace with an appropriate type
contentDigest: createContentDigest(currentElection),
},
})
// data for previous electionsfilePath
const previousElections = await SSR_getPreviousElections(apiBaseUrl, accessToken)
// remove current election from this array
const lastElections = previousElections?.data?.filter(e => e.id !== currentElection.id).slice(0, electionsToShow);
if (lastElections && lastElections.length > 0) {
let candidates = [];
let goldCandidates = [];
// create paths
fs.mkdirSync(prevElectionsBasePath, { recursive: true } );
fs.mkdirSync(`${prevElectionsBasePath}/candidates`, { recursive: true } );
fs.mkdirSync(`${prevElectionsBasePath}/candidates/gold`, { recursive: true } );
// Get current markdown files
const existingElectionFiles = fs.readdirSync(prevElectionsBasePath).filter(file => file.endsWith('.md'));
const existingCandidateFiles = fs.readdirSync(`${prevElectionsBasePath}/candidates`).filter(file => file.endsWith('.md'));
const existingGoldCandidateFiles = fs.readdirSync(`${prevElectionsBasePath}/candidates/gold`).filter(file => file.endsWith('.md'));
const lastElectionIds = lastElections.map(election => `${election.id}`);
// Function to check if filename contains any of the last election IDs
const filenameContainsElectionId = (filename, electionIds) => electionIds.some(id => filename.includes(id));
// Delete election files not included on the last elections to show
existingElectionFiles.forEach(file => {
if (!filenameContainsElectionId(file, lastElectionIds)) {
try {
fs.unlinkSync(path.join(prevElectionsBasePath, file));
console.log(`Deleted outdated election file: ${file}`);
} catch (err) {
console.error(`Error deleting file ${file}:`, err);
}
}
});
// Delete candidate files not included on the last elections to show
existingCandidateFiles.forEach(file => {
if (!filenameContainsElectionId(file, lastElectionIds)) {
try {
fs.unlinkSync(path.join(prevElectionsBasePath, 'candidates', file));
console.log(`Deleted outdated candidate file: ${file}`);
} catch (err) {
console.error(`Error deleting file ${file}:`, err);
}
}
});
// Delete gold candidate files not included on the last elections to show
existingGoldCandidateFiles.forEach(file => {
if (!filenameContainsElectionId(file, lastElectionIds)) {
try {
fs.unlinkSync(path.join(prevElectionsBasePath, 'candidates', 'gold', file));
console.log(`Deleted outdated gold candidate file: ${file}`);
} catch (err) {
console.error(`Error deleting file ${file}:`, err);
}
}
});
for (const election of lastElections) {
function formatMarkdown(post) {
const { body } = post
delete post.body
return
}
const seoObject = {
image: "/img/OpenInfra-icon-white.jpg",
twitterUsername: "@OpenInfraDev"
}
const electionYear = moment(election.closes * 1000).utc().format('YYYY');
// create MD file using yaml ...
if(!fs.existsSync(`${prevElectionsBasePath}/${election.id}.md`))
fs.writeFileSync(`${prevElectionsBasePath}/${election.id}.md`, `---\n${yaml.stringify({
templateKey: 'election-page-previous',
electionYear:electionYear,
electionId:election.id,
title:election.name,
seo: {
...seoObject,
title: election.name,
url: `https://openinfra.dev/election/${electionYear}-individual-director-election`,
description: `Individual Member Director elections for the ${electionYear} Board of Directors`
}
})}---\n`, 'utf8', function (err) {
if (err) {
console.log(err);
}
});
// create MD file using yaml ...
if(!fs.existsSync(`${prevElectionsBasePath}/candidates/${election.id}_candidates.md`))
fs.writeFileSync(`${prevElectionsBasePath}/candidates/${election.id}_candidates.md`, `---\n${yaml.stringify({
templateKey: 'election-candidates-page-previous',
electionYear:electionYear,
electionId:election.id,
title:`${election.name} Candidates`,
seo: {
...seoObject,
title: election.name,
url: `https://openinfra.dev/election/${electionYear}-individual-director-election/candidates`,
description: `Individual Member Director elections for the ${electionYear} Board of Directors`
}})}---\n`, 'utf8', function (err) {
if (err) {
console.log(err);
}
});
if(!fs.existsSync(`${prevElectionsBasePath}/candidates/gold/${election.id}_gold_candidates.md`))
fs.writeFileSync(`${prevElectionsBasePath}/candidates/gold/${election.id}_gold_candidates.md`, `---\n${yaml.stringify({
templateKey: 'election-gold-candidates-page-previous',
electionYear:electionYear,
electionId:election.id,
title:`${election.name} Gold Candidates`,
seo: {
...seoObject,
title: election.name,
url: `https://openinfra.dev/election/${electionYear}-individual-director-election/candidates/gold`,
description: `Individual Member Director elections for the ${electionYear} Board of Directors`
}})}---\n`, 'utf8', function (err) {
if (err) {
console.log(err);
}
});
const electionCandidates = await SSR_getPreviousElectionCandidates(apiBaseUrl, accessToken, election.id);
const electionGoldCandidates = await SSR_getPreviousElectionGoldCandidates(apiBaseUrl, accessToken, election.id);
if (Array.isArray(electionCandidates?.data) && electionCandidates?.data?.length > 0) candidates = [...candidates, ...electionCandidates.data];
if (Array.isArray(electionGoldCandidates?.data) && electionGoldCandidates?.data?.length > 0) goldCandidates = [...goldCandidates, ...electionGoldCandidates.data];
}
// ingest api data on graphql ...
lastElections.forEach(election => {
console.log(`gatsby-node.js::sourceNodes creating node for election ${JSON.stringify(election)}`)
createNode({
...election,
id: `${election.id}`,
parent: null,
children: [],
internal: {
type: 'ElectionData', // Replace with an appropriate type
contentDigest: createContentDigest(election),
},
});
})
candidates.forEach(candidate => {
createNode({
...candidate,
id: createNodeId(`CandidateData-${candidate.member.id}-${candidate.election_id}`),
election_id: `${candidate.election_id}`,
parent: null,
children: [],
internal: {
type: 'CandidateData', // Replace with an appropriate type
contentDigest: createContentDigest(candidate),
},
});
})
goldCandidates.forEach(candidate => {
createNode({
...candidate,
id: createNodeId(`GoldCandidateData-${candidate.member.id}-${candidate.election_id}`),
election_id: `${candidate.election_id}`,
parent: null,
children: [],
internal: {
type: 'GoldCandidateData', // Replace with an appropriate type
contentDigest: createContentDigest(candidate),
},
});
})
}
};
// explicit Frontmatter declaration to make category, author and date, optionals.
exports.createSchemaCustomization = ({actions}) => {
const {createTypes} = actions
const typeDefs = `
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
category: [Category]
author: String
date: Date @dateformat
featuredProjects: MarkdownRemarkFrontmatterFeaturedProjects
hero: MarkdownRemarkFrontmatterHero
sponsorshipSection: MarkdownRemarkFrontmatterSponsorshipSection
whatToExpect: MarkdownRemarkFrontmatterWhatToExpect
row1: MarkdownRemarkFrontmatterRow1
row2: MarkdownRemarkFrontmatterRow2
row3: MarkdownRemarkFrontmatterRow3
row4: MarkdownRemarkFrontmatterRow4
row5: MarkdownRemarkFrontmatterRow5
row6: MarkdownRemarkFrontmatterRow6
members: [MarkdownRemarkFrontmatterMembers]
}
type Category {
label: String
}
type SpeakerType {
name: String
company: String
presentationTitle: String
presentationLink: String
pic: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterFeaturedSpeakers {
title: String!
speakers: [SpeakerType!]!
}
type MarkdownRemarkFrontmatterHero {
subtitle: String
title: String
tagline: String
description: String
buttonText: String
buttonURL: String
}
type MarkdownRemarkFrontmatterWhatToExpect{
title: String
text: String
bullets: String
}
type MarkdownRemarkFrontmatterFeaturedProjects{
title: String
text: String
}
type SponsorshipSectionLeftColumn{
title: String
body: String
footer: String
}
type SponsorshipSectionRightColumn{
title: String
body: String
footer: String
}
type MarkdownRemarkFrontmatterSponsorshipSection{
title: String
text: String
leftColumn: SponsorshipSectionLeftColumn
rightColumn: SponsorshipSectionRightColumn
}
type MarkdownRemarkFrontmatterCompanyDetailsCompanies{
col1: String
col2: Date @dateformat
}
type ElectionData implements Node {
opens: Int
closes: Int
nominationOpens: Int
nominationCloses: Int
nominationApplicationDeadline: Int
}
type CandidateDataMember implements Node {
id: ID!
first_name: String!
last_name: String!
pic: String
bio: String
}
type GoldCandidateDataMember implements Node {
id: ID!
first_name: String!
last_name: String!
pic: String
bio: String
}
# Define the main JSON type for summits
type SummitsJson implements Node @dontInfer {
jsonId: Int!
featured_speakers: [FeaturedSpeaker]
summit_sponsors: [SummitSponsor]
}
type FeaturedSpeaker @dontInfer {
first_name: String
last_name: String
company: String
pic: String
}
type SummitSponsor @dontInfer {
sponsorship: Sponsorship
company: SponsorCompany
}
type Sponsorship @dontInfer {
id: String
order: Int
}
type SponsorCompany @dontInfer {
name: String
url: String
logo: String
big_logo: String
}
type MarkdownRemarkFrontmatterUpcomingMeetupsMeetups {
background: File @fileByRelativePath
date: String
location: String
link: String
}
type MarkdownRemarkFrontmatterUpcomingMeetupsBannerButton {
text: String
url: String
}
type MarkdownRemarkFrontmatterUpcomingMeetupsBanner {
title: String
content: String
button: MarkdownRemarkFrontmatterUpcomingMeetupsBannerButton
}
type MarkdownRemarkFrontmatterUpcomingMeetups {
title: String
banner: MarkdownRemarkFrontmatterUpcomingMeetupsBanner
meetups: [MarkdownRemarkFrontmatterUpcomingMeetupsMeetups]
}
# Resolve frontmatter seo.image path (string) to File so childImageSharp/publicURL work
type MarkdownRemarkFrontmatterSeo @infer {
image: File @fileByRelativePath
}
# Summit/summit-coming-soon/vancouver header and form image/icon as File
type MarkdownRemarkFrontmatterHeaderDate @infer {
icon: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterHeaderLocation @infer {
icon: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterHeader @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterForm @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterTopicsTopicList @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterPreviousSummitsSummitList @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSponsorshipsSponsorList @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterAbout @infer {
image: File @fileByRelativePath
}
# Summit-landing-page: resolve image/background/src to File
type MarkdownRemarkFrontmatterHeaderImage @infer {
backgroundImage: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterHeaderImageLogo @infer {
src: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSubHeaderBadge @infer {
src: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSubHeaderFooter @infer {
src: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSponsorBanner @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterPastSummitsSummits @infer {
background: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterMiddleBanner @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterPreviousSummitsSummits @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterBottomBanner @infer {
background: File @fileByRelativePath
}
# Other templates: resolve image/picture/logo/img to File where inferred as String
type MarkdownRemarkFrontmatterRow1Images @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterRow2Images @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterIndividualMember @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterCommunitiesLogos @infer {
img: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterInvolvedSlide @infer {
picture: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterHeadlineSponsorsSponsors @infer {
logo: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSupportingSponsorsSponsors @infer {
logo: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterMembers @infer {
name: String
picture: File @fileByRelativePath
logoUrl: String
link: String
}
type MarkdownRemarkFrontmatterWhyJoinItems @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterQuotePeople @infer {
picture: File @fileByRelativePath
company: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterHelp @infer {
picture: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterUpcomingDaysEventsHeaderImage @infer {
img: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterUpcomingMeetupsMeetups @infer {
background: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterPastMeetupsMeetups @infer {
background: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterProjectList @infer {
logo: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterProjectListFeatures @infer {
icon: File @fileByRelativePath
}
# Row types with all optional fields for services-page template
type MarkdownRemarkFrontmatterRow1 @infer {
title1: String
text1: String
title2: String
text2: String
images: [MarkdownRemarkFrontmatterRow1Images]
}
type MarkdownRemarkFrontmatterRow2 @infer {
title: String
text: String
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterRow3 @infer {
title: String
text: String
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterRow4 @infer {
title: String
text1: String
text2: String
link: MarkdownRemarkFrontmatterRow4Link
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterRow4Link {
url: String
text: String
}
type MarkdownRemarkFrontmatterRow5 @infer {
title: String
text1: String
text2: String
text3: String
link1: MarkdownRemarkFrontmatterRow5Link
link2: MarkdownRemarkFrontmatterRow5Link
images: [MarkdownRemarkFrontmatterRow5Images]
}
type MarkdownRemarkFrontmatterRow5Link {
text: String
url: String
}
type MarkdownRemarkFrontmatterRow5Images @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterRow6 @infer {
title1: String
text1: String
title2: String
text2: String
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterBanner @infer {
image: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterSupportMembers @infer {
picture: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterOpenInfraEventsData @infer {
logo: File @fileByRelativePath
}
type MarkdownRemarkFrontmatterUpcomingEvents @infer {
image: File @fileByRelativePath
}
`
createTypes(typeDefs)
}
exports.createPages = ({actions, graphql}) => {
const { createPage, createRedirect} = actions;
const getElectionPath = (templateKey, electionYear) => {
const electionTemplates = ['election-page-previous', 'election-page'];
const candidatesTemplates = ['election-candidates-page-previous', 'election-candidates-page'];
const goldCandidatesTemplates = ['election-gold-candidates-page-previous', 'election-gold-candidates-page'];
if(electionTemplates.includes(templateKey)) return `/election/${electionYear}-individual-director-election`;
if(candidatesTemplates.includes(templateKey)) return `/election/${electionYear}-individual-director-election/candidates`;
if(goldCandidatesTemplates.includes(templateKey)) return `/election/${electionYear}-individual-director-election/candidates/gold`;
}
const electionQuery = graphql(`
{
allMarkdownRemark(
limit: 1000
filter: {frontmatter: {templateKey: {in: ["election-page", "election-candidates-page", "election-gold-candidates-page"]}}}
) {
edges {
node {
id
fields {
slug
}
frontmatter {
title
templateKey
}
}
}
}
currentElectionData {
electionYear
}
}
`).then(result => {
console.log(`createPage res ${JSON.stringify(result)}`);
if (result.errors) {
result.errors.forEach(e => console.error(e.toString()))
return Promise.reject(result.errors)
}
const electionsPages = result.data.allMarkdownRemark.edges;
const electionYear = result.data.currentElectionData.electionYear;
electionsPages.forEach(edge => {
const id = edge.node.id;
const electionPath = getElectionPath(edge.node.frontmatter.templateKey, electionYear);
console.log(`createPage processing edge ${JSON.stringify(edge)} path ${electionPath}`);
createPage({
path: electionPath,
component: path.resolve(
`src/templates/${String(edge.node.frontmatter.templateKey)}.js`
),
// additional data can be passed via context
context: {
id
},
})
});
createRedirect({
fromPath: `/election/`,
toPath: `/election/${electionYear}-individual-director-election`,
});
createRedirect({
fromPath: `/election/candidates`,
toPath: `/election/${electionYear}-individual-director-election/candidates`,
});
createRedirect({
fromPath: `/election/candidates/gold`,
toPath: `/election/${electionYear}-individual-director-election/candidates/gold`,
});
// Redirect deleted project pages to /about
createRedirect({
fromPath: `/projects/services`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/services/*`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/funding`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/funding/*`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/contact`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/contact/*`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/hosting`,
toPath: `/about`,
isPermanent: true,
});
createRedirect({
fromPath: `/projects/hosting/*`,
toPath: `/about`,
isPermanent: true,
});
});
const previousElectionQuery = graphql(`
{
allMarkdownRemark(
limit: 1000
filter: {frontmatter: {templateKey: {in: ["election-page-previous", "election-candidates-page-previous", "election-gold-candidates-page-previous"]}}}
) {
edges {
node {
id
fields {
slug
}
frontmatter {
title
templateKey
electionId
electionYear
}
}
}
}
}
`).then(result => {
console.log(`createPage res ${JSON.stringify(result)}`);
if (result.errors) {
result.errors.forEach(e => console.error(e.toString()))
return Promise.reject(result.errors)
}
const electionsPages = result.data.allMarkdownRemark.edges;
electionsPages.forEach(edge => {
const id = edge.node.id;
const electionId = edge.node.frontmatter.electionId.toString();
const electionYear = edge.node.frontmatter.electionYear;
const electionPath = getElectionPath(edge.node.frontmatter.templateKey, electionYear);
console.log(`createPage processing edge ${JSON.stringify(edge)} path ${electionPath}`);
createPage({
path: electionPath,
component: path.resolve(
`src/templates/${String(edge.node.frontmatter.templateKey)}.js`
),
// additional data can be passed via context
context: {
id,
electionId
},
})
})
});
const allPagesQuery = graphql(`
{
allMarkdownRemark(limit: 1000, filter: {frontmatter: {electionId: {eq: null}, templateKey: {nin: ["election-page", "election-candidates-page", "election-gold-candidates-page"]}}}) {
edges {
node {
id
fields {
slug
}
frontmatter {
category {
label
}
title
author
templateKey
seo {
url
}
}
}
}
}
}
`).then(result => {
if (result.errors) {
result.errors.forEach(e => console.error(e.toString()))
return Promise.reject(result.errors)
}
const pages = result.data.allMarkdownRemark.edges;
pages.forEach(edge => {
if (edge.node.frontmatter.templateKey) {
const id = edge.node.id;
const SEO = edge.node.frontmatter.seo ? edge.node.frontmatter.seo : null;
const slug = getPageSlugFromSEO(SEO, edge.node.fields.slug);
createPage({
path: slug,
category: edge.node.frontmatter.category,
component: path.resolve(
`src/templates/${String(edge.node.frontmatter.templateKey)}.js`
),
// additional data can be passed via context
context: {
id
},
})
}
})
// category pages:
let categories = JSON.parse(fs.readFileSync('src/content/blog-config.json')).categories;
// Make category pages
categories.forEach(c => {
const category = c.text;
const categoriePath = `/blog/category/${_.kebabCase(category)}/`
createPage({
path: categoriePath,
component: path.resolve(`src/templates/tags.js`),
context: {
category,
},
})
})
// author pages:
let authors = []
// Iterate through each post, putting all found authors into `authors`
pages.forEach(edge => {