// 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')
    }
})

postRouter.post('/',async (req,res)=>{
    if(req.session.user){
        post.postItem(req,res)
    }else{
        res.redirect('/login')
    }
})

export default postRouter

 

// controllers/admin/post.js
import config from '../../config.js'
import categorydb from '../../models/category.js'
import postdb from '../../models/post.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)
        this.config.count = await postdb.count(req)
        this.config.items = await postdb.getItem(req,this.config.maxPosts)

        res.render('base',{data:this.config})
    }

    async postItem(req,res){
        await postdb.postItem(req)
        res.redirect('/admin/post')
    }
}

export default new Post()

 

// models/post.js

class Post{
    async count(req){
        return await req.mydb.collection('posts').countDocuments()
    }

    async postItem(req){
        const id = Date.now() + Math.round(Math.random() * 1E9).toString()

        if(req.body.categories.includes(',')){
            var categories = req.body.categories.split(',')
        }else{
            var categories = [req.body.categories]
        }
        
        let newPost = {
            id: id, 
            title: req.body.title,
            content: req.body.content,
            categories: categories,
            price: req.body.price,
            thumb: req.body.thumb,
            phone: req.body.phone,
            email: req.body.email,
            postdate: req.body.datetime,
            video: req.body.entries,
            userid: req.session.user.id,
        }
 
        await req.mydb.collection("posts").insertOne(newPost)
    }

    async getItem(req,amount){
        return await req.mydb.collection("posts").find().sort({date:-1,_id:-1}).limit(amount).toArray()
    }
}

export default new Post()

 

 

Heroku: https://khmerweb-sale.herokuapp.com/login