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

export default new Post()

 

GitHub: https://github.com/Sokhavuth/Node.js_backend

Vercel: https://vercel.com/sokhavuth/node-js-backend