@opengis/fastify-table
Version:
core-plugins
118 lines (117 loc) • 3.52 kB
JavaScript
import path from "node:path";
import getMeta from "../../../plugins/pg/funcs/getMeta.js";
import dataInsert from "../../../plugins/crud/funcs/dataInsert.js";
import dataUpdate from "../../../plugins/crud/funcs/dataUpdate.js";
import { applyHook } from "../../../../utils.js";
import uploadMultiPart from "../../../plugins/file/uploadMultiPart.js";
const tableList = {
comment: "crm.communications",
gallery: "crm.files",
file: "crm.files",
checklist: "crm.checklists",
reaction: "crm.reactions",
};
const pkList = {
comment: "communication_id",
checklist: "checklist_id",
file: "file_id",
gallery: "file_id",
reaction: "reaction_id",
};
const galleryExtList = [
"png",
"svg",
"jpg",
"jpeg",
"gif",
"mp4",
"mov",
"avi",
];
export default async function widgetSet(req, reply) {
const { pg, params, headers = {}, body = {}, user = {}, } = req;
const { type, id, objectid } = params || {};
if (!pkList[type] || !tableList[type]) {
return reply.status(400).send("param type not valid");
}
if (!objectid) {
return reply.status(400).send("not enough params: id");
}
const table = tableList[type];
// dsadasdad
if (["gallery", "file"].includes(type) &&
headers["content-type"]?.split?.(";")?.shift?.() === "multipart/form-data") {
const file = await uploadMultiPart(req);
const extName = path
.extname(file.filepath || "")
.slice(1)
.toLowerCase();
const data = {
uploaded_name: file?.originalFilename
?.toLocaleLowerCase()
?.replace(/'/g, "''"),
file_path: file?.relativeFilepath?.replace(/\\/g, "/"),
ext: extName,
size: file?.size,
file_status: 1,
uid: user?.uid || 1,
entity_id: objectid,
};
if (type === "gallery" && !galleryExtList.includes(extName.toLowerCase())) {
return reply.status(400).send("invalid file extension");
}
const { rows = [] } = await dataInsert({
pg,
table: "crm.files",
data,
uid: user?.uid,
});
if (type === "gallery") {
await pg.query(`update crm.files set ismain=true
where entity_id=$1
and file_id=$2
and (select count(*) = 0 from crm.files where entity_id=$1 and ismain)`, [objectid, rows[0]?.file_id]);
}
return {
rowCount: 1,
data: "ok",
command: "UPLOAD",
id: rows[0]?.file_id,
entity_id: rows[0]?.entity_id,
};
}
const { pk } = await getMeta({ pg, table });
if (!pk) {
return reply.status(404).send("table not found");
}
const data = { ...body, uid: user?.uid, entity_id: objectid };
await applyHook("onWidgetSet", {
pg,
link: req.path,
id,
objectid,
user,
type,
payload: data,
});
const result = id
? await dataUpdate({
pg,
table,
data,
id,
uid: user?.uid,
})
: await dataInsert({
pg,
table,
data,
uid: user?.uid,
});
return reply.status(200).send({
rowCount: result.rowCount,
data: "ok",
command: result.command,
id: result.rows?.[0]?.[pkList[type]] || result?.[pkList[type]],
});
}