Files
cms.techvanguard.vn/controllers/_createPageContentController.js
T
Tống Thành Đạt 7e01fba2c3 chore(controllers): disable json file writing on page content updates
Disable the automatic writing of data to JSON files in `createPageContentController`, `admissionsController`, and `policiesController` to prevent redundant file system operations during updates.
2026-04-23 13:43:53 +07:00

122 lines
3.9 KiB
JavaScript

const { addBaseUrlToImages } = require("../utils/imageHelper");
const jsonHelper = require("../utils/jsonHelper");
const writeAuditLog = require("../audit/writeAuditLog");
const diffObject = require("../audit/diffObject");
function createPageContentController({
model,
modelName,
auditAction,
editorConfig,
normalizeForEditor,
normalizeForApi,
preparePayload,
}) {
return {
async index(req, res) {
try {
const doc = await model.getSingle();
const rawData = doc.toObject();
const data = normalizeForEditor ? normalizeForEditor(rawData, req) : rawData;
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";
const backendUrl =
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
res.render("admin/pageContent/index", {
layout: "layouts/main",
title: editorConfig.title,
subtitle: editorConfig.subtitle,
data,
editorConfig,
activeTab: req.query.tab || editorConfig.tabs[0].key,
frontendUrl,
backendUrl,
previewUrl: `${frontendUrl}${editorConfig.previewPath}`,
currentPath: req.path,
user: req.session.user,
});
} catch (error) {
console.error(`${editorConfig.key} index error:`, error);
req.flash("error_msg", `Error loading ${editorConfig.title}`);
return req.session.save(() => res.redirect("/admin/dashboard"));
}
},
async update(req, res) {
try {
const rawPayload =
typeof req.body.pageJson === "string"
? JSON.parse(req.body.pageJson)
: req.body.pageJson || {};
const activeTab = req.body.activeTab || editorConfig.tabs[0].key;
const doc = await model.getSingle();
const beforeData = JSON.parse(JSON.stringify(doc.toObject()));
const payload = preparePayload
? preparePayload(rawPayload, { req, doc, beforeData })
: rawPayload;
doc.set(payload);
Object.keys(payload).forEach((key) => doc.markModified(key));
await doc.save();
const afterData = JSON.parse(JSON.stringify(doc.toObject()));
const changes = diffObject(beforeData, afterData);
if (changes.length > 0) {
await writeAuditLog({
model: modelName,
documentId: doc._id,
action: auditAction,
before: beforeData,
after: afterData,
changes,
req,
});
}
// const finalData = await model
// .findOne()
// .select("-_id -__v -createdAt -updatedAt")
// .lean();
// jsonHelper.writeJsonFile(editorConfig.dataFile, finalData);
req.flash("success_msg", `${editorConfig.title} updated successfully`);
return req.session.save(() =>
res.redirect(`${editorConfig.routeBase}?tab=${activeTab}`),
);
} catch (error) {
console.error(`${editorConfig.key} update error:`, error);
req.flash(
"error_msg",
`Error updating ${editorConfig.title}: ${error.message}`,
);
return req.session.save(() =>
res.redirect(
`${editorConfig.routeBase}?tab=${req.body.activeTab || ""}`,
),
);
}
},
async api(req, res) {
try {
const doc = await model.getSingle();
const rawData = doc.toObject();
const backendUrl =
process.env.BACKEND_URL ?? `${req.protocol}://${req.get("host")}`;
const normalized = normalizeForApi ? normalizeForApi(rawData, req) : rawData;
const processed = addBaseUrlToImages(normalized, backendUrl);
return res.json(processed);
} catch (error) {
console.error(`${editorConfig.key} api error:`, error);
return res
.status(500)
.json({ error: `Error loading ${editorConfig.key} data` });
}
},
};
}
module.exports = createPageContentController;