UNPKG

@tachybase/module-workflow

Version:

A powerful BPM tool that provides foundational support for business automation, with the capability to extend unlimited triggers and nodes.

231 lines (230 loc) 8.99 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var UpdateOrCreateInstruction_exports = {}; __export(UpdateOrCreateInstruction_exports, { UpdateOrCreateInstruction: () => UpdateOrCreateInstruction, default: () => UpdateOrCreateInstruction_default }); module.exports = __toCommonJS(UpdateOrCreateInstruction_exports); var import_server = require("@tego/server"); var import_axios = __toESM(require("axios")); var import_form_data = __toESM(require("form-data")); var import_lodash = __toESM(require("lodash")); var import_mime_types = __toESM(require("mime-types")); var import__ = require("."); var import_constants = require("../constants"); var import_utils = require("../utils"); class UpdateOrCreateInstruction extends import__.Instruction { async run(node, input, processor) { var _a, _b, _c, _d; const { collection, params: { appends = [], ...params } = {} } = node.config; const [dataSourceName, collectionName] = (0, import_server.parseCollectionName)(collection); const { repository, filterTargetKey } = this.workflow.app.dataSourceManager.dataSources.get(dataSourceName).collectionManager.getCollection(collectionName); const options = processor.getParsedValue(params, node.id); const transaction = this.workflow.useDataSourceTransaction(dataSourceName, processor.transaction); const c = this.workflow.app.dataSourceManager.dataSources.get(dataSourceName).collectionManager.getCollection(collectionName); const fields = c.getFields(); const fieldNames = Object.keys(params.values); const includesFields = fields.filter((field) => fieldNames.includes(field.options.name)); const userId = import_lodash.default.get(processor.getScope(node.id), "$context.user.id", ""); const token = this.workflow.app.authManager.jwt.sign({ userId }); const isJSON = (str) => { try { return JSON.parse(str); } catch (e) { return false; } }; const handleResource = async (resource) => { if (typeof resource === "object" && (resource == null ? void 0 : resource.url) && (resource == null ? void 0 : resource.filename)) { const { id, createdAt, updatedAt, title, filename, extname, size, mimetype, path, meta, url, createById, updatedById, storageId } = resource || {}; return { id, createdAt, updatedAt, title, filename, extname, size, mimetype, path, meta, url, createById, updatedById, storageId }; } const parseRes = isJSON(resource); const config = { method: "get", url: resource, responseType: "stream" }; const form = new import_form_data.default(); if (resource.startsWith("data:")) { const matches = resource.match(/^data:(.+);base64,(.+)$/); if (matches) { const contentType = matches[1]; const base64Data = matches[2]; const buffer = Buffer.from(base64Data, "base64"); const ext = import_mime_types.default.extension(contentType); const filename = `${(0, import_server.uid)()}.${ext}`; form.append("file", buffer, { filename, contentType }); } else { throw new Error("Invalid data URL format"); } } else if (parseRes) { const { url: resourceUrl, params: resourceParams, headers: resourceHeaders, body: resourceBody, filename } = parseRes; config.url = resourceUrl; config.params = resourceParams; config.headers = resourceHeaders; if (resourceHeaders["content-type"] === "multipart/form-data") { const formData = new import_form_data.default(); Object.entries(resourceBody).forEach(([key, value]) => { formData.append(key, value); }); config.data = formData; } else { config.data = resourceBody; } const response = await (0, import_axios.default)(config); const contentType = response.headers["content-type"]; const ext = import_mime_types.default.extension(contentType); const fullFilename = `${filename || (0, import_server.uid)()}.${ext}`; form.append("file", response.data, { filename: fullFilename, contentType: response.headers["content-type"] }); } else { const response = await (0, import_axios.default)(config); const contentType = response.headers["content-type"]; const ext = import_mime_types.default.extension(contentType); const filename = `${(0, import_server.uid)()}.${ext}`; form.append("file", response.data, { filename, contentType: response.headers["content-type"] }); } const origin = import_server.Gateway.getInstance().runAtLoop; const uploadResponse = await (0, import_axios.default)({ method: "post", url: origin + "/api/attachments:create", data: form, headers: { ...form.getHeaders(), Authorization: "Bearer " + token } }); return uploadResponse.data.data; }; for (const attachmentField of includesFields) { if (attachmentField.options.interface === "attachment") { let targetField = options.values[attachmentField.options.name]; if (Array.isArray(targetField)) { for (const i in targetField) { targetField[i] = await handleResource(targetField[i]); } } else { options.values[attachmentField.options.name] = [await handleResource(targetField)]; } } } const instance = await repository.findOne({ filter: options.filter, transaction }); if (instance) { const result = await repository.update({ ...options, context: { stack: Array.from(new Set((processor.execution.context.stack ?? []).concat(processor.execution.id))), state: (_b = (_a = processor.options) == null ? void 0 : _a.httpContext) == null ? void 0 : _b.state }, transaction }); return { result: result.length ?? result, status: import_constants.JOB_STATUS.RESOLVED }; } else { const created = await repository.create({ ...options, context: { stack: Array.from(new Set((processor.execution.context.stack ?? []).concat(processor.execution.id))), state: (_d = (_c = processor.options) == null ? void 0 : _c.httpContext) == null ? void 0 : _d.state }, transaction }); let result = created; if (created && appends.length) { const includeFields = appends.reduce((set, field) => { set.add(field.split(".")[0]); set.add(field); return set; }, /* @__PURE__ */ new Set()); result = await repository.findOne({ filterByTk: created[filterTargetKey], appends: Array.from(includeFields), transaction }); } return { // NOTE: get() for non-proxied instance (#380) result: (0, import_utils.toJSON)(result), status: import_constants.JOB_STATUS.RESOLVED }; } } } var UpdateOrCreateInstruction_default = UpdateOrCreateInstruction; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { UpdateOrCreateInstruction });