// routes/admin.js
import express from 'express'
const adminRouter = express.Router()
import postRouter from './admin/post.js'
adminRouter.use('/post',postRouter)
import categoryRouter from './admin/category.js'
adminRouter.use('/category',categoryRouter)
export default adminRouter
// routes/admin/post.js
import express from 'express'
const postRouter = express.Router()
import post from '../../controllers/admin/post.js'
postRouter.get('/',async (req,res)=>{
if(req.session.user){
post.getItem(req,res)
}else{
res.redirect('/login')
}
})
export default postRouter
// controllers/admin/post.js
import config from '../../config.js'
import categorydb from '../../models/category.js'
class Post{
async getItem(req,res){
this.config = await config()
this.config.pageTitle = 'ទំព័រទំនិញ'
this.config.route = '/admin/post'
this.config.type = 'post'
this.config.categories = await categorydb.getAllItem(req)
res.render('base',{data:this.config})
}
}
export default new Post()
// 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 getAllItem(req){
return await req.mydb.collection("categories").find().sort({title:1}).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)
}
async deleteItem(req){
await req.mydb.collection("categories").deleteOne({id:req.params.id})
}
async paginateItem(req,amount){
const page = req.body.page
return await req.mydb.collection("categories").find().skip(amount*page).sort({date:-1,_id:-1}).limit(amount).toArray()
}
}
export default new Category()