import { stringifyJSON } from 'cpb-common';
import stream from 'stream';
import { StorageInstance as storage } from '../shared.js';
/**
* ###streaming file upload
* @method module:cpb-storage/file.upload
* @async
* @param {?string} [bucket=process.env.BUCKET || 'custom-product-builder'] - storage bucket
* @param {!string} name - filename for the uploaded file in bucket
* @param {!*} data - data to be uploaded
* @param {?string} [contentType='application/json'] - file content type
* @param {?function} [callback]
* @param {?object} [metadata={}] - file metadata
* @returns {Promise<void>}
*/
export default async function UploadFile({
bucket = process.env.BUCKET || 'custom-product-builder',
name,
data,
contentType = 'application/json',
callback,
metadata = {},
} = {}) {
if (!bucket) throw new TypeError('!bucket');
if (!name) throw new TypeError('!name');
if (!data) throw new TypeError('!data');
// if (!data) throw new TypeError('!data');
const myBucket = storage.bucket(bucket),
file = myBucket.file(name),
pStream = new stream.PassThrough();
try {
pStream.write(Buffer.from(stringifyJSON(data, { indent: 2 })));
pStream.end();
} catch (e) {
console.error('ERROR.UploadFile', { data, e });
throw e;
}
async function streamFileUpload() {
pStream
.pipe(
file.createWriteStream({
metadata: {
...metadata,
contentType,
},
}),
)
.on('finish', d => {
console.debug(`streamFileUpload.onFinish::${bucket}/${name}`);
if (callback) return callback({ name, bucket, d });
return true;
});
}
return await streamFileUpload().catch(console.error);
}