Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var NCMB = require('ncmb');
- module.exports = function(req, res) {
- var application_key = req.query.application_key;
- var client_key = req.query.client_key;
- var ncmb = new NCMB(application_key, client_key);
- var ClassName = ncmb.DataStore(req.query.className);
- var d = new Date;
- var filename = req.query.className + "_" + d.getFullYear() + (d.getMonth() + 1) + d.getDate() + ".csv";
- var user = new ncmb.User({userName: req.query.userName, password: req.query.password});
- user.login()
- .then(function(user) {
- var data = [];
- var limit = 1000;
- var loop = function(page) {
- return new Promise(function(resolve, reject) {
- ClassName
- .limit(limit)
- .skip(limit * page)
- .fetchAll()
- .then(function(results) {
- if (Object.keys(results).length == 0) {
- return resolve(true);
- }
- for (var i in results) {
- data.push(results[i]);
- }
- loop(page + 1)
- .then(function() {
- resolve(true);
- }, function(error) {
- reject(error);
- })
- })
- .catch(function(error) {
- reject(error);
- })
- });
- }
- loop(0)
- .then(function() {
- csv = [];
- header = [];
- for(var i in data) {
- var ary = Object.keys(data[i]);
- for (var j in ary) {
- if (ary[j] == 'acl') {
- continue;
- }
- if (header.indexOf(ary[j]) < 0) {
- header.push(ary[j]);
- }
- }
- }
- csv = [header.join("\t")];
- for(var i in data) {
- var row = data[i];
- var line = [];
- for (var j in header) {
- if (header[j] == 'acl') {
- continue;
- }
- var val = row[header[j]];
- switch (typeof val) {
- case 'boolean':
- case 'number':
- line.push(val)
- break;
- case 'object':
- switch (val.__type) {
- case 'Date':
- line.push(val.iso);
- break;
- case 'GeoPoint':
- line.push(val.latitude + "," + val.longitude);
- break;
- default:
- line.push(JSON.stringify(val).replace(/"/g, '""'));
- break;
- }
- break;
- default:
- try {
- line.push((val || "").replace(/"/g, '""'))
- }catch(e){
- console.log(val, typeof val)
- }
- }
- }
- csv.push('"' + line.join('"\t"') + '"');
- }
- // var blob = new Blob(csv.join("\r\n"), {type: "text/csv"});
- buf = new Buffer(csv.join("\r\n"), 'UTF-8');
- ncmb.File.upload(filename, buf)
- .then(function() {
- res.status(200).json("アップロードされました。" + filename);
- })
- .catch(function(error) {
- console.log(error)
- })
- }, function(error) {
- res.status(500).json(error);
- });
- })
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement