-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgoogleSpreadsheet.js
More file actions
75 lines (68 loc) · 2.17 KB
/
googleSpreadsheet.js
File metadata and controls
75 lines (68 loc) · 2.17 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
const google = require('googleapis');
const keys = require('./config/keys');
const marked = require('marked');
const spreadsheetDataId = '1QHKa3vUpht7zRl_LEzl3BlUbolz3ZiL8yKHzdBL42dY';
const spreadsheetLink = `https://docs.google.com/spreadsheets/d/${spreadsheetDataId}/edit`;
let loadedItems = [];
// creates a dictionary mapping column names with the values
// ex: { floor : 402, business : coworking, etc..}
function spreadsheetValuesToObject(values, columns, index) {
const formatedRow = {};
for (let i = 0; i < columns.length; i += 1) {
formatedRow[columns[i]] = values[i];
}
formatedRow.cellRef = `${spreadsheetLink}#gid=0&range=A${index}:T${index}`;
return formatedRow;
}
function loadDatabase(callback) {
const sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: keys.apiKey,
spreadsheetId: spreadsheetDataId,
range: 'Agora inventory!A:Z',
}, (err, response) => {
if (err) {
console.log(`The API returned an error: ${err}`);
return;
}
const columns = response.values[0];
let i = 0;
loadedItems = response.values.map((row) => {
i += 1;
return spreadsheetValuesToObject(row, columns, i);
});
return callback();
});
}
function searchDatabase(query, callback) {
if (loadedItems.length === 0) {
// if the database was not loaded load it then recall this function with the same parameters
// warning, this causes an infinite loop if the spreadsheet is empty or unreachable
loadDatabase(() => searchDatabase(query, callback));
return;
}
let queryResult = loadedItems;
Object.keys(query).map((key) => {
queryResult = loadedItems.filter(item => item[key] === query[key]);
});
return callback(queryResult);
}
function addSimilarItems(items) {
const obj = items;
obj.similarItems = loadedItems.filter(item => item.fixture === obj.fixture)
.filter(item => item.uuid !== obj.uuid)
.splice(0, 3);
return obj;
}
function addMarkdown(items) {
const obj = items;
obj.HOWTO = marked(obj.HOWTO);
obj.details = marked(obj.details);
obj.Troubleshooting = marked(obj.Troubleshooting);
return obj;
}
module.exports = {
searchDatabase,
addMarkdown,
addSimilarItems,
};