// 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')
}
})
categoryRouter.get('/edit/:id',async (req,res)=>{
if(req.session.user){
category.editItem(req,res)
}else{
res.redirect('/login')
}
})
categoryRouter.post('/edit/:id',async (req,res)=>{
if(req.session.user){
category.updateItem(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')
}
async editItem(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.item = await categorydb.editItem(req)
this.config.items = await categorydb.getItem(req,this.config.maxPosts)
res.render('base',{data:this.config})
}
async updateItem(req,res){
if(req.session.user.role === 'Admin'){
await categorydb.updateItem(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()
}
async editItem(req){
return await req.mydb.collection('categories').findOne({id:req.params.id})
}
async updateItem(req){
let myquery = {id: req.params.id}
let newvalue = {$set: {
title: req.body.title,
thumb: req.body.thumb,
postdate: req.body.datetime
}}
await req.mydb.collection("categories").updateOne(myquery,newvalue)
}
}
export default new Category()