-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (57 loc) · 1.91 KB
/
server.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
// server.js
// where your node app starts
// We're going to use the "Product Catalog and Orders" base template:
// https://airtable.com/templates/featured/expZvMLT9L6c4yeBX/product-catalog-and-orders
var Airtable = require('airtable');
var base = new Airtable({
apiKey: process.env.AIRTABLE_API_KEY,
}).base(process.env.AIRTABLE_BASE_ID);
//var tableName = 'Furniture';
//var viewName = 'Main View';
var tableName = 'Event';
var viewName = 'Table';
var express = require('express');
var app = express();
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function(request, response) {
response.sendFile(__dirname + '/views/index.html');
});
// Cache the records in case we get a lot of traffic.
// Otherwise, we'll hit Airtable's rate limit.
var cacheTimeoutMs = 5 * 1000; // Cache for 5 seconds.
var cachedResponse = null;
var cachedResponseDate = null;
app.get("/data", function(_, response) {
if (cachedResponse && new Date() - cachedResponseDate < cacheTimeoutMs) {
response.send(cachedResponse);
} else {
// Select the first 10 records from the view.
base(tableName).select({
maxRecords: 10,
view: viewName,
}).firstPage(function(error, records) {
if (error) {
response.send({error: error});
} else {
cachedResponse = {
records: records.map(record => {
return {
name: record.get('Title'),
picture: record.get('Image'),
description: record.get('Description'),
owner: record.get('Owner'),
};
}),
};
cachedResponseDate = new Date();
response.send(cachedResponse);
}
});
}
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function() {
console.log('Your app is listening on port ' + listener.address().port);
});