refactor: add auto-generated menu for new services

This commit is contained in:
Đỗ Minh Nhật
2026-04-11 05:45:07 +07:00
parent e7929568dc
commit 0109b08b58
4 changed files with 106 additions and 15 deletions

View File

@@ -0,0 +1,57 @@
/**
* Sync HeaderMenu children of the "Services" menu item
* to match the current list of services in the database.
*
* Strategy:
* - Find the HeaderMenu item whose url === '/services'
* - Delete all its direct children
* - Re-create one child per service item (url = /services/<slug>)
*/
const HeaderMenu = require("../models/headerMenu");
const slugify = require("slugify");
/**
* @param {Array} serviceItems - array of service objects { slug, name }
*/
const syncServiceMenu = async (serviceItems = []) => {
try {
// 1. Find the "Services" parent menu item
const servicesParent = await HeaderMenu.findOne({ url: "/services" });
if (!servicesParent) {
console.warn("[syncServiceMenu] No HeaderMenu item with url=/services found. Skipping sync.");
return;
}
const parentId = servicesParent._id;
// 2. Remove all existing children of that parent
await HeaderMenu.deleteMany({ parentId });
// 3. Re-create one child per service
const ops = serviceItems
.filter((s) => s && s.slug && s.name)
.map((s, index) => ({
title: s.name,
slug: slugify(s.name, { lower: true, strict: true }),
url: `/services/${s.slug}`,
parentId,
order: index + 1,
status: "active",
type: "internal",
is_maintainance: false,
}));
if (ops.length > 0) {
await HeaderMenu.insertMany(ops);
}
console.log(`[syncServiceMenu] Synced ${ops.length} service menu items under parentId=${parentId}`);
} catch (err) {
// Non-fatal log but don't crash the main request
console.error("[syncServiceMenu] Error syncing service menu:", err.message);
}
};
module.exports = syncServiceMenu;