Skip to content

Instantly share code, notes, and snippets.

@marwinious
Last active January 28, 2020 18:18
Show Gist options
  • Select an option

  • Save marwinious/721c3fa4e54377718bb074a52df0dd5e to your computer and use it in GitHub Desktop.

Select an option

Save marwinious/721c3fa4e54377718bb074a52df0dd5e to your computer and use it in GitHub Desktop.
Vue.js: Google Sheets API store pattern module w/underscore
import {_} from 'underscore'
export default {
state: {
},
createGsApiUrl: function(gs_key, sheet_id) {
var gs_url = 'https://spreadsheets.google.com/feeds/list/'+gs_key+'/'+sheet_id+'/public/values?alt=json';
return gs_url;
},
normalizeGsData: function(gs) {
// INIT
var json = {};
json.data = [];
json.cellData = [];
json.feedType = 'list';
// PARSE JSON STRING TO OBJECT
if(_.isString(gs)) {
gs = JSON.parse(gs);
}
if(!_.isUndefined(gs.feed['gs$colCount'])) {
json.colCount = gs.feed['gs$colCount']['$t'];
json.rowCount = gs.feed['gs$rowCount']['$t'];
json.feedType = 'cells';
}
// CHECK IF ENTRIES EXIST
if(!_.isUndefined(gs.feed) && !_.isUndefined(gs.feed.entry)) {
// LOOP THROUGH ENTRIES (ROWS)
gs.feed.entry.forEach(function(entry) {
let loopData = {};
// IF "LIST" FEED
if(json.feedType == 'list') {
// LOOP THROUGH COLUMNS IN THIS ROW
Object.keys(entry).forEach(function(column) {
// IF ENTRY STARTS WITH "GSX$", IT IS A COLUMN FROM THE SPREADSHEET
if(column.substring(0,4) == 'gsx$') {
// ADD COLUMN NAME AND ROW CONTENT FOR COLUMN TO OBJECT
loopData[column.substring(4, column.length)] = entry[column]['$t'];
}
});
}
// IF "CELLS" FEED
else if(json.feedType == 'cells') {
// BUILD CELL-BY-CELL ARRAY (AN "ENTRY" FOR EVERY CELL. DATA[0]{DATA})
loopData = {
cell: entry['gs$cell']["$t"],
col: entry['gs$cell']["col"],
row: entry['gs$cell']["row"],
title: entry['title']["$t"]
};
// BUILD CELL ROW->COLUMNS ARRAY (AN "ENTRY" FOR EVERY ROW WITH THAT ROW'S COLUMNS INSIDE. DATA[ROW#][COL#]{DATA})
if(!_.isUndefined(json.cellData[loopData.row])) {
json.cellData[loopData.row] = [];
}
json.cellData[loopData.row][loopData.col] = {
cell: entry['gs$cell']["$t"],
title: entry['title']["$t"]
}
}
// SAVE LOOP DATA TO MAIN DATA ARRAY
json.data.push(loopData);
});
}
return json;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment