@onereach/orest-input-cli
Version:
The tool for creating, serving, and publishing OREST Inputs
132 lines (112 loc) • 2.65 kB
JavaScript
const ProgressBar = require('progress');
const StoreApi = require('./api/storeApi');
const path = require('path');
const progressConfig = {
complete: '=',
incomplete: ' ',
width: 30,
total: 100,
};
const uploadingBar = new ProgressBar(
'Uploading: [:bar] :percent :etas :fileName',
progressConfig
);
function onUploadProgress(progress, fileName = '') {
uploadingBar.update(Math.round(progress) / 100, { fileName });
}
function getUploadUrl({ storeApi, meta, destFileName, packageType }) {
const payload = {
...meta,
type: packageType,
fileName: destFileName,
};
return storeApi.getUploadCredentials(payload);
}
async function upload({
filePath,
destFileName,
meta,
userToken,
storeApiUrl,
packageType,
}) {
const storeApi = new StoreApi({
userToken,
storeApiUrl,
packageType,
});
if (!destFileName) {
destFileName = filePath.split('/').pop();
}
try {
const { url, fields } = await getUploadUrl({
meta,
storeApi,
destFileName,
packageType,
});
const res = await storeApi.uploadBundle(
{ filePath, destFileName, url, fields },
onUploadProgress
);
if (res.statusCode === 204) {
return true;
} else {
throw res.statusCode;
}
} catch (error) {
console.log('error', JSON.stringify(error, null, 2));
throw error;
}
}
function getUploadUrlSandbox({ fileNames, meta, storeApi, packageType }) {
const payload = {
...meta,
fileNames,
type: packageType,
};
return storeApi.getUploadCredentialsSandbox(payload);
}
async function uploadToSandbox({
fileNames,
relDirPath = '',
tempDirName = '',
meta,
userToken,
storeApiUrl,
packageType,
}) {
const storeApi = new StoreApi({
userToken,
storeApiUrl,
packageType,
});
const data = await getUploadUrlSandbox({
meta,
fileNames,
storeApi,
packageType,
});
const dataLength = data.length;
let uploadedCount = 0;
await Promise.all(
data.map(({ fileName, url, fields }) => {
const filePath = path.join(
path.resolve(process.cwd(), relDirPath),
tempDirName,
fileName
);
return storeApi.uploadBundle({ filePath, url, fields }).then(() => {
uploadedCount = ++uploadedCount;
const displayFileName = dataLength === uploadedCount ? '' : fileName;
onUploadProgress((uploadedCount / dataLength) * 100, displayFileName);
});
})
);
return await storeApi.getMetaByVersion({
id: meta.id,
version: meta.version,
});
}
exports.upload = upload;
exports.uploadToSandbox = uploadToSandbox;