UNPKG

@intuitionrobotics/file-upload

Version:

File Uploader - Express & Typescript based backend framework

116 lines 6.21 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.UploaderModule = exports.UploaderModule_Class = exports.Temp_Path = void 0; const ts_common_1 = require("@intuitionrobotics/ts-common"); const backend_1 = require("@intuitionrobotics/firebase/backend"); const types_1 = require("../../shared/types"); const UploaderTempFileModule_1 = require("./UploaderTempFileModule"); const backend_2 = require("@intuitionrobotics/push-pub-sub/backend"); exports.Temp_Path = "files-temp"; class UploaderModule_Class extends ts_common_1.Module { constructor() { super("UploaderModule"); this.setPostProcessor = (validator) => { this.postProcessor = validator; }; this.getProcessor = (k) => { const postProcessorElement = this.postProcessor[k]; if (!postProcessorElement) throw new ts_common_1.ImplementationMissingException(`Missing validator for type ${k}`); return postProcessorElement; }; this.fileUploaded = (filePath) => __awaiter(this, void 0, void 0, function* () { if (!filePath) throw new ts_common_1.ThisShouldNotHappenException("Missing file path"); this.logInfo(`Looking for file with path ${filePath}`); // I use collection and not the module directly since I want to handle failure my way const tempMeta = yield UploaderTempFileModule_1.UploaderTempFileModule.collection.queryUnique({ where: { path: filePath } }); if (!tempMeta) return this.logInfo(`File with path: ${filePath}, not found in temp collection db`); this.logInfo(`Found temp meta with _id: ${tempMeta._id}`, tempMeta); const val = this.postProcessor[tempMeta.key]; this.logInfo(`Found a validator ${!!val}`); if (!val) return this.notifyFrontend(tempMeta.feId, types_1.UploadResult.Failure, `Missing a validator for ${tempMeta.key} for file: ${tempMeta.name}`); const bucket = yield this.storage.getOrCreateBucket(tempMeta.bucketName); const file = yield bucket.getFile(tempMeta.path); if (tempMeta.public) { try { yield file.makePublic(); } catch (e) { yield this.notifyFrontend(tempMeta.feId, types_1.UploadResult.Failure, `Failed to make the file public: ${tempMeta.name}`, e); } } try { yield val(file, tempMeta); } catch (e) { //TODO delete the file and the temp doc return yield this.notifyFrontend(tempMeta.feId, types_1.UploadResult.Failure, `Post-processing failed for file: ${tempMeta.name}`, e); } return this.notifyFrontend(tempMeta.feId, types_1.UploadResult.Success, `Successfully parsed and processed file ${tempMeta.name}`); }); this.notifyFrontend = (feId, result, message, cause) => __awaiter(this, void 0, void 0, function* () { cause && this.logWarning(cause); const data = { message, result, cause }; yield backend_2.PushPubSubModule.pushToKey(types_1.fileUploadedKey, { feId }, data); }); } __onFileUploaded(filePath) { return __awaiter(this, void 0, void 0, function* () { yield this.fileUploaded(filePath); }); } init() { if (!this.postProcessor) throw new ts_common_1.ImplementationMissingException("You must set a postProcessor for the UploaderModule"); this.storage = backend_1.FirebaseModule.createAdminSession(this.config.uploaderProjectId).getStorage(); } getUrl(body_1) { return __awaiter(this, arguments, void 0, function* (body, pathPrefix = exports.Temp_Path, _bucketName) { var _a; const bucketName = _bucketName || ((_a = this.config) === null || _a === void 0 ? void 0 : _a.bucketName); const bucket = yield this.storage.getOrCreateBucket(bucketName); return Promise.all(body.map((_file) => __awaiter(this, void 0, void 0, function* () { const key = _file.key || _file.mimeType; this.getProcessor(key); const _id = (0, ts_common_1.generateHex)(32); const path = `${pathPrefix}/${_id}`; const instance = { _id, feId: _file.feId, name: _file.name, mimeType: _file.mimeType, key, path, _audit: (0, ts_common_1.auditBy)("be-stub"), bucketName: bucket.bucketName }; if (_file.public) instance.public = _file.public; if (_file.metadata) instance.metadata = _file.metadata; const temp = yield UploaderTempFileModule_1.UploaderTempFileModule.upsert(instance); const file = yield bucket.getFile(temp.path); const url = yield file.getWriteSecuredUrl(_file.mimeType, ts_common_1.Hour); return { secureUrl: url.securedUrl, tempDoc: temp }; }))); }); } } exports.UploaderModule_Class = UploaderModule_Class; exports.UploaderModule = new UploaderModule_Class(); //# sourceMappingURL=UploaderModule.js.map