This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
fetch-from-final-timeline-+-sources.js
162 lines (147 loc) · 3.93 KB
/
fetch-from-final-timeline-+-sources.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
const AirTable = require('airtable');
const dotEnv = require('dotenv');
const MONTHS = {
Jan: 1,
Feb: 2,
Mar: 3,
Apr: 4,
May: 5,
Jun: 6,
Jul: 7,
Aug: 8,
Sep: 9,
Oct: 10,
Nov: 11,
Dec: 12,
};
const CACHE_EXPIRATION = 5 * 60 * 1000; // 5 minutes in milliseconds
dotEnv.config();
AirTable.configure({
endpointUrl: 'https://api.airtable.com',
apiKey: process.env.AIRTABLE_API_KEY,
});
const base = AirTable.base('appnQs29Fzl3tWohJ');
const cache = {
events: null,
lastUpdated: Date.now(),
updatePending: false,
};
/**
* Event data is hosted on AirTable. this function attempts to both fetch and
* collate it into the format expected by TimelineJS3.
*
* @returns {Promise} Event data, formatted for TimelineJS3
*/
function fetchEvents() {
console.log('fetchEvents:start');
let sources;
return (
base
// Fetch all sources
.table('Sources')
.select({ view: 'Grid view' })
.all()
// Cache sources by id
.then(rows => {
sources = rows.reduce(
(acc, { id, fields }) => Object.assign({}, acc, { [id]: fields }),
{},
);
return;
})
// Fetch all timeline events
.then(() =>
base
.table('Timeline')
.select({ view: 'Grid view' })
.all(),
)
.then(rows => {
console.log('fetchEvents:end');
return rows;
})
// Transform sources and events to slide JSON
.then(rows =>
rows
.map(({ fields }) => fields)
.filter(
row =>
process.env.NODE_ENV === 'production'
? row.Status === 'Live'
: row.Status === 'Live' || row.Status === 'Staged',
)
.sort((a, b) => a.Year - b.Year)
.map(row => ({
start_date: {
day: row.Day,
month: MONTHS[row.Month],
year: row.Year,
display_date: null,
},
text: {
headline: row.Headline,
text: [
`<p>${row.Body || ''}</p>`,
...row.Sources.map(
sourceId =>
`<a href="${sources[sourceId].URL}">Source: ${sources[
sourceId
].Publication}</a>`,
),
].join('\n'),
},
media: {
url:
row['Media (URL)'] ||
(row['Media (Image)']
? row['Media (Image)'][0].thumbnails.large.url
: ''),
caption: row['Media (Caption)'] || '',
credit: row['Media (Credit)'] || '',
thumbnail: null,
},
tags: [],
background: {},
unique_id: row.ID,
})),
)
);
}
/**
* Update the event cache, asynchronously. Resolves with the new data, once
* updated.
*
* @returns {Promise} Event data, formatted for TimelineJS3
*/
function updateEventCache() {
cache.updatePending = true;
return fetchEvents().then(events => {
cache.events = events;
cache.lastUpdated = Date.now();
cache.updatePending = false;
return events;
});
}
/**
* It's expensive (and slow) to fetch events to service every request.
* Instead, this wrapper function attempts to load events from a cache first,
* triggering a request in the background, if the contents appear stale.
*
* @returns {Promise} Event data, formatted for TimelineJS3
*/
function fetchEventsWithCache() {
// If cache is stale, trigger an async update (but don't block on it).
if (
!cache.updatePending &&
Date.now() - cache.lastUpdated >= CACHE_EXPIRATION
) {
updateEventCache();
}
// If we have cached data, return it.
if (cache.events != null) {
return Promise.resolve(cache.events);
}
// If we have never cached data yet, fetch and block on the result.
return updateEventCache();
}
module.exports = fetchEventsWithCache;