Files
cms.uldp.edu.vn/services/syncServiceMenu.js
2026-04-13 06:00:54 +07:00

58 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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/details/${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;