libre
Version:
World's lightest CMS
116 lines (90 loc) • 3.14 kB
JavaScript
//See https://www.npmjs.com/package/google-spreadsheet
import GoogleSpreadsheet from 'google-spreadsheet';
import async from 'async';
export default class Sheet {
constructor(creds) {
this.creds = creds;
this.sheet = {};
this.model = {};
}
loadSheet(key, sheetName, success) {
const doc = new GoogleSpreadsheet(key);
const me = this;
me.sheet = null;
async.series([
(step) => doc.useServiceAccountAuth(me.creds, step),
(step) => {
doc.getInfo((err, info) => {
// console.log(`Loaded Google Spreadsheet: ${info.title} (owned by ${info.author.email})`);
info.worksheets.map((ws, idx) => {
if (ws.title.trim().toLowerCase() == sheetName) me.sheet = info.worksheets[idx];
});
if (me.sheet != null) {
console.log(`[SHEET] Ingesting content from [${me.sheet.title}]...`);
me.ingest(success);
}
else {
console.log(`Sheet ${sheetName} not found!`);
}
});
}
]);
}
ingest(success) {
const me = this;
//Load ALL rows in the sheet into more accessible data structure in memory
//This way we don't have to hit the spreadsheet every time (faster, more efficient, fewer API calls etc)
me.sheet.getRows({}, (err, rows) => {
//model object is for individual lookup; lessons are for sequential tutorial
//flatModel is the same data but without .parent and .children properties added to rows, which create circular references
//we need to use flatModel anytime we transfer data (e.g., REST API)
me.model = {};
for (var i=0; i < rows.length; i++) {
var row = JSON.parse(JSON.stringify(rows[i]));
row.content = (row.content) ? row.content.split('\n') : [];
//delete some extra crap added by Google. we want just the data in the sheet
delete row['_xml'];
delete row['app:edited'];
delete row['_links'];
//every row object is available in root of model, with item field as unique primary key
me.model[row.id] = row;
}
success(me.model);
});
}
validate() {
//review id field and keywords fields for non-unique content
var ids = [];
var dupes = [];
for (var k in this.model) {
if (ids.indexOf(k) > -1) {
idDupes.push(k);
}
ids.push(k);
}
return {dupes};
}
addRow(key, tab, row, success) {
const doc = new GoogleSpreadsheet(key);
var sheetIndex = -1;
async.series([
(step) => doc.useServiceAccountAuth(this.creds, step),
(step) => {
doc.getInfo((err, info) => {
// console.log(`Loaded Google Spreadsheet: ${info.title} (owned by ${info.author.email})`);
info.worksheets.map((ws, idx) => {
if (ws.title.trim().toLowerCase() == tab.toLowerCase()) sheetIndex = idx + 1;
});
if (sheetIndex > 0) {
doc.addRow(sheetIndex, row, (err) => {
if (!err) success();
});
}
else {
console.log(`Sheet ${tab} not found!`);
}
});
}
]);
}
}