//routes/admin/category.js
import express from 'express'
const categoryRouter = express.Router()
import category from '../../controllers/admin/category.js'
categoryRouter.get('/',async (req,res)=>{
if(req.session.user){
category.getItem(req,res)
}else{
res.redirect('/login')
}
})
categoryRouter.post('/',async (req,res)=>{
if(req.session.user){
category.postItem(req,res)
}else{
res.redirect('/login')
}
})
export default categoryRouter
// controllers/admin/category.js
import config from "../../config.js"
import categorydb from '../../models/category.js'
class Category{
async getItem(req,res){
this.config = await config()
this.config.pageTitle = 'ទំព័រប្រភេទទំនិញ'
this.config.route = '/admin/category'
this.config.type = 'category'
this.config.count = await categorydb.count(req)
this.config.items = await categorydb.getItem(req,this.config.maxPosts)
res.render('base',{data:this.config})
}
async postItem(req,res){
await categorydb.postItem(req)
res.redirect('/admin/category')
}
}
export default new Category()
// models/category.js
class Category{
async count(req){
return await req.mydb.collection('categories').countDocuments()
}
async postItem(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
let newCategory = {
id: id,
title: req.body.title,
thumb: req.body.thumb,
postdate: req.body.datetime
}
await req.mydb.collection("categories").insertOne(newCategory)
}
async getItem(req,amount){
return await req.mydb.collection("categories").find().sort({date:-1,_id:-1}).limit(amount).toArray()
}
}
export default new Category()