Created
November 18, 2016 08:48
-
-
Save goofmint/422a8faedb952d724730d52ab7569b85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"') + '"'); | |
} | |
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); | |
}); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment