//routes/backend/post.js
import express from 'express'
const postRouter = express.Router()
import post from '../../controllers/backend/post.js'
postRouter.get('/', async function(req,res){
await post.getPage(req,res)
})
postRouter.post('/', async function(req,res){
await post.createItem(req,res)
})
export default postRouter
//controllers/backend/post.js
import category from '../../models/category.js'
import post from '../../models/post.js'
class Post{
async getPage(req,res){
req.settings.pageTitle = 'ទំព័រការផ្សាយ'
req.settings.message = ''
req.settings.route = '/admin/post'
req.settings.type = 'post'
req.settings.categories = await category.getItem(req,'all')
req.settings.items = await post.getItem(req,req.settings.dItemLimit)
req.settings.count = await post.countItem(req)
res.render('base', {data:req.settings})
}
async createItem(req,res){
if(req.session.user){
post.createItem(req)
res.redirect('/admin/post')
}else{
res.redirect('/admin/login')
}
}
}
export default new Post()
//models/post.js
class Post{
async createItem(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
let categories = []
if(req.body.categories.includes(',')){
let str = req.body.categories.replace(/\s+/g, "")
categories = str.split(',')
}else{
categories = [req.body.categories]
}
const new_post = {
id: id,
title: req.body.title,
content: req.body.content,
categories: categories,
thumb: req.body.thumb,
date: req.body.datetime,
videos: req.body.videos,
userid: req.session.user.id,
}
await req.mydb.collection("posts").insertOne(new_post)
}
async countItem(req){
return await req.mydb.collection('posts').countDocuments()
}
async getItem(req,amount=10,id=false){
if(id){
return await req.mydb.collection("posts").findOne({id:id})
}else if(req.body.page){
let page = req.body.page
return await req.mydb.collection("posts").find().skip(amount*page).sort({date:-1,_id:-1}).limit(amount).toArray()
}else if(amount === 'all'){
return await req.mydb.collection("posts").find({}, {title:1,_id:0}).sort({title:1}).toArray()
}else{
return await req.mydb.collection("posts").find().sort({date:-1,_id:-1}).limit(amount).toArray()
}
}
}
export default new Post()