Files
mbmanager-api/components/category/categoryService.js
T

96 lines
2.8 KiB
JavaScript

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')
}
module.exports.createCategory = async (data) => {
const category = Category.create(data, null)
return category
}
module.exports.getCategory = async (categoryId) => {
const category = await Category.findById(categoryId)
if (!category) {
throw new AppError('NoCategoryFound', 404, {})
}
return category
}
module.exports.updateCategory = async (categoryId, data) => {
const category = await Category.findOneAndUpdate({ _id: categoryId }, data, { new: true })
if (!category) {
throw new AppError('NoCategoryFound', 404, {})
}
return category
}
module.exports.deleteCategory = async (categoryId) => {
const category = await Category.findByIdAndDelete(categoryId)
if (!category) {
throw new AppError('NoCategoryFound', 404, {})
}
return null
}