@platform/cell.client
Version:
A strongly typed HTTP client for operating with a CellOS service end-point.
78 lines (77 loc) • 4.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadToTarget = void 0;
var tslib_1 = require("tslib");
var common_1 = require("../common");
function uploadToTarget(args) {
var _this = this;
var http = args.http, fire = args.fire, urls = args.urls, files = args.files;
return urls
.map(function (upload) {
var file = files.find(function (item) { return item.filename === upload.filename; });
var data = file === null || file === void 0 ? void 0 : file.data;
return { data: data, upload: upload };
})
.filter(function (_a) {
var data = _a.data;
return Boolean(data);
})
.map(function (_a) {
var upload = _a.upload, data = _a.data;
return tslib_1.__awaiter(_this, void 0, void 0, function () {
var url, path, uploadToS3, uploadToLocal, res, ok, status, uri, filename, expiresAt, error, message;
var _this = this;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
url = upload.url;
path = upload.props.key;
uploadToS3 = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var props, contentType, form, isNode, payload, headers;
return tslib_1.__generator(this, function (_a) {
props = upload.props;
contentType = props['content-type'];
form = new common_1.FormData();
Object.keys(props)
.map(function (key) { return ({ key: key, value: props[key] }); })
.forEach(function (_a) {
var key = _a.key, value = _a.value;
return form.append(key, value);
});
isNode = typeof Buffer !== 'undefined';
if (!isNode) {
throw new Error("Upload from browser not (yet) supported.");
}
payload = isNode ? Buffer.from(data) : data;
form.append('file', payload, { contentType: contentType });
headers = form.getHeaders();
return [2, http.post(url, form, { headers: headers })];
});
}); };
uploadToLocal = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var headers;
return tslib_1.__generator(this, function (_a) {
headers = { 'content-type': 'multipart/form-data', path: path };
return [2, http.post(url, data, { headers: headers })];
});
}); };
return [4, (upload.filesystem === 'S3' ? uploadToS3() : uploadToLocal())];
case 1:
res = _b.sent();
ok = res.ok, status = res.status;
uri = upload.uri, filename = upload.filename, expiresAt = upload.expiresAt;
if (!ok) {
message = "Client failed while uploading file '".concat(filename, "' (").concat(status, ")");
error = { type: 'FILE/upload', filename: filename, message: message };
}
fire({
file: { filename: filename, uri: uri },
error: error ? { status: status, type: 'HTTP/file', message: error.message } : undefined,
});
return [2, { ok: ok, status: status, uri: uri, filename: filename, expiresAt: expiresAt, error: error }];
}
});
});
});
}
exports.uploadToTarget = uploadToTarget;