Guest User

Untitled

a guest
Jan 18th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. const functions = require('firebase-functions');
  2.  
  3.  
  4. const admin = require('firebase-admin');
  5. admin.initializeApp(functions.config().firebase);
  6. const es = require('event-stream')
  7. const Parser = require('newline-json').Parser
  8. const gcs = require('@google-cloud/storage')();
  9. const path = require('path');
  10.  
  11. // [START function]
  12. exports.generateData = functions.storage.object().onChange(event => {
  13. const object = event.data; // The Storage object.
  14.  
  15. const fileBucket = object.bucket; // The Storage bucket that contains the file.
  16. const filePath = object.name; // File path in the bucket.
  17. const contentType = object.contentType; // File content type.
  18. const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
  19. const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
  20.  
  21. // Exit if this is triggered on a file that is not JSON.
  22. if (!contentType.endsWith('json')) {
  23. console.log('This is not a json file.');
  24. return;
  25. }
  26.  
  27. // Exit if this is a move or deletion event.
  28. if (resourceState === 'not_exists') {
  29. console.log('This is a deletion event.');
  30. return;
  31. }
  32.  
  33. // Exit if file exists but is not new and is only being triggered
  34. // because of a metadata change.
  35. if (resourceState === 'exists' && metageneration > 1) {
  36. console.log('This is a metadata change event.');
  37. return;
  38. }
  39.  
  40. // Download file from bucket.
  41. const bucket = gcs.bucket(fileBucket);
  42.  
  43. let buf = []
  44.  
  45. const getStream = function () {
  46. let stream = bucket.file(filePath).createReadStream().on('error', () => { console.log('Read Error')}).on('end', () => {console.log('Successful Read')})
  47. let parser = new Parser()
  48. return stream.pipe(parser)
  49. }
  50.  
  51. getStream()
  52. .pipe(es.mapSync(function (data) {
  53. buf.push(data)
  54. pump()
  55. }))
  56. .on('end', () => {
  57. console.log("Strem Finished")
  58. return true
  59. })
  60. .on('error', () => {
  61. console.log('Stream Error')
  62. return false
  63. })
  64.  
  65. function pump() {
  66. let pos;
  67.  
  68. while((pos = buf.length) >= 1) {
  69. processLine(buf.pop(0))
  70. }
  71. }
  72.  
  73. function processLine(line) {
  74. admin.firestore().collection('test').add(line)
  75. }
  76.  
  77. });
Add Comment
Please, Sign In to add comment