From 8a04d92ecba64b1c72a836bd15ce80dd1c177dd8 Mon Sep 17 00:00:00 2001 From: Bing Sun Date: Mon, 27 Apr 2020 23:30:07 +0800 Subject: [PATCH] add export method to model --- src/postgrest.js | 40 ---------------------------------------- src/util/make_model.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 40 deletions(-) diff --git a/src/postgrest.js b/src/postgrest.js index 21538a5..4523c0a 100644 --- a/src/postgrest.js +++ b/src/postgrest.js @@ -1,43 +1,3 @@ -// utilities -// generate downloadable csv -const download = (options={}) => { - options.filename = options.filename || 'file' - - if (options.type == 'csv') { - let headers = Object.keys(options.data[0]) - - let body = options.data.map(row => headers.map(key => row[key]).join(',')).join('\n') - - options.data = '\ufeff' + headers.join(',') + '\n' + body - options.type = 'text/csv' - } else if (options.type == 'json') { - } - - let blob = new Blob([options.data], {type: options.type}) - let url = URL.createObjectURL(blob) - - if (options.timestamp) - options.filename = options.filename + (new Date()).toLocaleTimeString(undefined, { - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hour12: false - }) - - let anchor = document.createElement('a') - anchor.href = url - anchor.target = '_blank' - anchor.download = `${options.filename}.csv` - - anchor.click() - - URL.revokeObjectURL(url) - anchor.remove() -} - // authentication model const _make_auth = api_root => { diff --git a/src/util/make_model.js b/src/util/make_model.js index 487eb6b..a15845e 100644 --- a/src/util/make_model.js +++ b/src/util/make_model.js @@ -208,6 +208,44 @@ export default (options={}) => { }) return _promise + }, + + export(options={}) { + options.filename = options.filename || _configs.endpoint + let _data = this.data() + + if (options.type == 'csv') { + let headers = _configs.selects && _configs.selects.map(select => select.alias || select.label) || Object.keys(_data[0]) + + let body = _data.map(row => headers.map(key => row[key]).join(',')).join('\n') + + _data = '\ufeff' + headers.join(',') + '\n' + body + options.type = 'text/csv' + } + + let blob = new Blob([_data], {type: options.type}) + let url = URL.createObjectURL(blob) + + if (options.timestamp) + options.filename = options.filename + (new Date()).toLocaleTimeString(undefined, { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false + }) + + let anchor = document.createElement('a') + anchor.href = url + anchor.target = '_blank' + anchor.download = `${options.filename}.csv` + + anchor.click() + + URL.revokeObjectURL(url) + anchor.remove() } }