-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
240 lines (223 loc) · 7.49 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
const { google } = require('googleapis');
const maps = require("@googlemaps/google-maps-services-js").Client;
const moment = require('moment');
const fs = require('fs');
const requiredFields = ['id', 'internal'];
const googleMapsClient = new maps({});
const defaultOptions = {
includedFields: ['start', 'end', 'summary', 'status', 'organizer', 'description', 'location', 'slug'],
calendarId: '',
assumedUser: '',
geoCodeApiKey: process.env.GOOGLE_MAPS_API_KEY,
envVar: '',
pemFilePath: '',
// only events after today
timeMin: moment().format(),
// only events two years from now
timeMax: moment().add(2, 'y').format(),
scopes: [
`https://www.googleapis.com/auth/calendar.events.readonly`,
`https://www.googleapis.com/auth/calendar.readonly`
]
};
const forbiddenChars = [',', '!', '#', '?', '.'];
const getLongAndLat = (key, event) => {
return googleMapsClient
.geocode({
params: {
address: event.location,
key
}
})
.then((data) => {
const coordinates = data.data.results.find((result) => result.geometry.location);
if (coordinates) {
return coordinates.geometry.location;
}
else {
return null;
}
})
.catch((e) => {
console.error(`error fetching long and lat for ${event.location}: ${e}`);
return null;
});
};
const getSlug = (event) => {
const summary = event.summary
.split(" ")
.map((word) => {
return word
.toLowerCase()
.split('')
.filter((char) => !forbiddenChars.includes(char))
.join('')
})
.join("-");
const date = event.start.date
? event.start.date
: moment(event.start.dateTime).format('MM-DD-YYYY');
return `${date}/${summary}`;
};
const processEventObj = (event, fieldsToInclude) => {
return Object.keys(event)
.reduce((acc, key) => {
if (fieldsToInclude.concat(requiredFields).includes(key)) {
return {
...acc,
[key]: event[key]
};
}
return acc;
}, {});
};
const getAuth = (options) => {
if (options.envVar) return JSON.parse(options.envVar);
if (fs.existsSync(options.pemFilePath)) {
return require(options.pemFilePath);
}
}
exports.sourceNodes = async ({ actions }, options = defaultOptions) => {
const key = getAuth(options);
const { createNode } = actions
const {
assumedUser,
calendarId,
includedFields,
timeMax,
timeMin,
geoCodeApiKey,
scopes
} = { ...defaultOptions, ...options };
// setting the general auth property for client
const token = new google.auth.JWT(
key.client_email,
null,
key.private_key,
scopes,
assumedUser
);
google.options({ auth: token });
// getting the calendar client
const calendar = google.calendar('v3');
// getting the list of items for calendar
const { data: { items }} = await calendar.events.list({
calendarId: calendarId,
showDeleted: false,
// ascending
orderBy: 'starttime',
// recurring events are duplicated
singleEvents: true,
timeMin: timeMin,
timeMax: timeMax
});
const parseEventCoordinateString = (str) => str
.split(" ")
.map((word) => {
return word
.toLowerCase()
.split('')
.filter((char) => !forbiddenChars.includes(char))
.join('')
})
.join("-");
const getEventCoordinates = (events) => new Promise((resolve, reject) => {
const locationData = {};
events
.reduce((prevPromise, event, i, arr) => {
if (!event.location) return Promise.resolve();
const eventLocationString = parseEventCoordinateString(event.location);
return prevPromise
.then((data) => {
if (data === 'init') {
return getLongAndLat(geoCodeApiKey, event)
.then((data) => {
locationData[eventLocationString] = data;
});
}
if (Object.keys(locationData).includes(eventLocationString)) {
if (i === arr.length - 1) {
return resolve(locationData);
}
return Promise.resolve();
}
else {
return getLongAndLat(geoCodeApiKey, event)
.then((data) => {
locationData[eventLocationString] = data;
if (i === arr.length - 1) resolve(locationData);
});
}
})
.catch((e) => {
console.error(`gatsby-source-google-calendar-events error during network request: ${e}`);
reject(e);
});
}, Promise.resolve('init'));
});
// Process data into nodes.
getEventCoordinates(items)
.then((locationData) => {
items
.map((event) => {
const eventSlug = getSlug(event);
const eventCoordinateKey = event.location
? parseEventCoordinateString(event.location)
: '';
const longAndLat = Object.keys(locationData).includes(eventCoordinateKey)
? locationData[eventCoordinateKey]
: null
return {
...event,
slug: eventSlug,
geoCoordinates: longAndLat,
internal: {
contentDigest: event.updated,
type: 'GoogleCalendarEvent'
}
};
})
.forEach(event => {
const eventObj = processEventObj(event, includedFields);
createNode(eventObj);
})
})
// We're done, return.
return
};
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
createTypes(`
type EventAttachment implements Node {
fileUrl: String
title: String
}
type EventTime implements Node {
date: Date,
dateTime: Date,
timeZone: String
}
type EventCoordinates implements Node {
lat: Float
lng: Float
}
type GoogleCalendarEvent implements Node {
id: ID
name: String
slug: String
status: String
start: EventTime
end: EventTime
summary: String
status: String
organizer: String
description: String
location: String
attachments: [EventAttachment]
geoCoordinates: EventCoordinates
admin: Boolean
created: Date
photo: File
}
`)
};