-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstorage.js
More file actions
86 lines (78 loc) · 2.12 KB
/
storage.js
File metadata and controls
86 lines (78 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { Storage } from '@google-cloud/storage'
import { Transform } from 'stream'
import zlib from 'zlib'
const storage = new Storage()
export class StorageUpload {
constructor (bucket) {
this.bucket = bucket
}
async exportToJson (stream, fileName) {
const bucket = storage.bucket(this.bucket)
const file = bucket.file(fileName)
let first = true
let batch = []
const BATCH_SIZE = 1000
const jsonTransform = new Transform({
writableObjectMode: true,
transform (chunk, encoding, callback) {
batch.push(chunk)
if (batch.length >= BATCH_SIZE) {
let str = ''
if (first) {
str = '[\n ' + JSON.stringify(batch[0])
for (let i = 1; i < batch.length; i++) {
str += ',\n ' + JSON.stringify(batch[i])
}
first = false
} else {
for (let i = 0; i < batch.length; i++) {
str += ',\n ' + JSON.stringify(batch[i])
}
}
batch = []
callback(null, str)
} else {
callback()
}
},
flush (callback) {
let str = ''
if (batch.length > 0) {
if (first) {
str = '[\n ' + JSON.stringify(batch[0])
for (let i = 1; i < batch.length; i++) {
str += ',\n ' + JSON.stringify(batch[i])
}
first = false
} else {
for (let i = 0; i < batch.length; i++) {
str += ',\n ' + JSON.stringify(batch[i])
}
}
}
if (first) {
str += '[]'
} else {
str += '\n]'
}
callback(null, str)
}
})
const gzip = zlib.createGzip()
await new Promise((resolve, reject) => {
stream
.pipe(jsonTransform)
.pipe(gzip)
.pipe(file.createWriteStream({
metadata: {
contentEncoding: 'gzip'
}
}))
.on('error', reject)
.on('finish', () => {
console.info(`File ${fileName} successfully written to ${this.bucket}`)
resolve()
})
})
}
}