Advertisement
Guest User

Untitled

a guest
Feb 6th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.28 KB | None | 0 0
  1. var NCMB = require('ncmb');
  2.  
  3. module.exports = function(req, res) {
  4. var application_key = req.query.application_key;
  5. var client_key = req.query.client_key;
  6. var ncmb = new NCMB(application_key, client_key);
  7. var ClassName = ncmb.DataStore(req.query.className);
  8. var d = new Date;
  9. var filename = req.query.className + "_" + d.getFullYear() + (d.getMonth() + 1) + d.getDate() + ".csv";
  10. var user = new ncmb.User({userName: req.query.userName, password: req.query.password});
  11. user.login()
  12. .then(function(user) {
  13. var data = [];
  14. var limit = 1000;
  15. var loop = function(page) {
  16. return new Promise(function(resolve, reject) {
  17. ClassName
  18. .limit(limit)
  19. .skip(limit * page)
  20. .fetchAll()
  21. .then(function(results) {
  22. if (Object.keys(results).length == 0) {
  23. return resolve(true);
  24. }
  25. for (var i in results) {
  26. data.push(results[i]);
  27. }
  28. loop(page + 1)
  29. .then(function() {
  30. resolve(true);
  31. }, function(error) {
  32. reject(error);
  33. })
  34. })
  35. .catch(function(error) {
  36. reject(error);
  37. })
  38. });
  39. }
  40. loop(0)
  41. .then(function() {
  42. csv = [];
  43. header = [];
  44. for(var i in data) {
  45. var ary = Object.keys(data[i]);
  46. for (var j in ary) {
  47. if (ary[j] == 'acl') {
  48. continue;
  49. }
  50. if (header.indexOf(ary[j]) < 0) {
  51. header.push(ary[j]);
  52. }
  53. }
  54. }
  55. csv = [header.join("\t")];
  56. for(var i in data) {
  57. var row = data[i];
  58. var line = [];
  59. for (var j in header) {
  60. if (header[j] == 'acl') {
  61. continue;
  62. }
  63. var val = row[header[j]];
  64. switch (typeof val) {
  65. case 'boolean':
  66. case 'number':
  67. line.push(val)
  68. break;
  69. case 'object':
  70. switch (val.__type) {
  71. case 'Date':
  72. line.push(val.iso);
  73. break;
  74. case 'GeoPoint':
  75. line.push(val.latitude + "," + val.longitude);
  76. break;
  77. default:
  78. line.push(JSON.stringify(val).replace(/"/g, '""'));
  79. break;
  80. }
  81. break;
  82. default:
  83. try {
  84. line.push((val || "").replace(/"/g, '""'))
  85. }catch(e){
  86. console.log(val, typeof val)
  87. }
  88. }
  89. }
  90. csv.push('"' + line.join('"\t"') + '"');
  91. }
  92. // var blob = new Blob(csv.join("\r\n"), {type: "text/csv"});
  93. buf = new Buffer(csv.join("\r\n"), 'UTF-8');
  94. ncmb.File.upload(filename, buf)
  95. .then(function() {
  96. res.status(200).json("アップロードされました。" + filename);
  97. })
  98. .catch(function(error) {
  99. console.log(error)
  100. })
  101. }, function(error) {
  102. res.status(500).json(error);
  103. });
  104.  
  105. })
  106. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement