ADD: get category tree logic function
This commit is contained in:
@@ -1,6 +1,60 @@
|
||||
const Category = require('./categoryModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
module.exports.getCategoryTree = async () => {
|
||||
const nodes = await Category.find({})
|
||||
let tree = []
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
if (!nodes[i].parentId) {
|
||||
const label = nodes[i].nativeName
|
||||
const children = []
|
||||
const key = nodes[i]._id.toString()
|
||||
const href = '/categories/admin/update/' + nodes[i]._id
|
||||
const a_attr = { href }
|
||||
const root = { label, children, key, a_attr }
|
||||
tree.push(root)
|
||||
}
|
||||
}
|
||||
|
||||
tree = recursiveFunction(tree, nodes)
|
||||
return tree
|
||||
}
|
||||
|
||||
const recursiveFunction = (tree, categories) => {
|
||||
if (tree.length > 0) {
|
||||
for (let i = 0; i < tree.length; i++) {
|
||||
let subTree = []
|
||||
for (let j = 0; j < categories.length; j++) {
|
||||
if (tree[i].key === categories[j].parentId?.toString()) {
|
||||
const label = categories[j].nativeName.toString()
|
||||
const children = []
|
||||
const key = categories[j]._id.toString()
|
||||
const href = '/categories/admin/update/' + categories[j]._id
|
||||
const a_attr = { href }
|
||||
subTree.push({ label, children, key, a_attr })
|
||||
}
|
||||
let index = findCategoryIndex(tree, tree[i].label)
|
||||
tree[index].children = subTree
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < tree.length; i++) {
|
||||
let index = findCategoryIndex(tree, tree[i].label)
|
||||
recursiveFunction(tree[index].children, categories)
|
||||
}
|
||||
}
|
||||
return tree
|
||||
}
|
||||
|
||||
function findCategoryIndex(array, label) {
|
||||
let index
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (array[i].label === label) {
|
||||
index = i
|
||||
return index
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.getAllCategories = async () => {
|
||||
return Category.find().populate('parentId')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user