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

postRouter.get('/edit/:id', async function(req,res){
    await post.getPage(req,res)
})

postRouter.post('/edit/:id', async function(req,res){
    await post.updateItem(req,res)
})

postRouter.get('/delete/:id', async function(req,res){
    await post.deleteItem(req,res)
})

postRouter.post('/paginate', async function(req,res){
    await post.paginateItem(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)
        
        if(req.params.id){
            req.settings.item = await post.getItem(req,req.settings.dItemLimit,req.params.id)
        }
        
        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')
        }
    }

    async updateItem(req,res){
        if((req.session.user.role == "Author")||(req.session.user.role == "Admin")){
            const postdb = await post.getItem(req,req.settings.dItemLimit,req.params.id)
            if((req.session.user.id == postdb.userid)||(req.session.user.role == "Admin")){
                await post.updateItem(req)
                res.redirect("/admin/post")
            }
        }else{
            res.redirect("/admin/login")
        }
    }

    async deleteItem(req,res){
        if((req.session.user.role == "Author")||(req.session.user.role == "Admin")){
            const postdb = await post.getItem(req,req.settings.dItemLimit,req.params.id)
            if((req.session.user.id == postdb.userid)||(req.session.user.role == "Admin")){
                await post.deleteItem(req)
                res.redirect("/admin/post")
            }
        }else{
            res.redirect("/admin/login")
        }
    }

    async paginateItem(req,res){
        if(req.session.user){
            req.settings.type = 'post'
            req.settings.items = await post.getItem(req,req.settings.dItemLimit)
            res.json(req.settings)
        }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()
        }
    }

    async updateItem(req){
        const myquery = {id:req.params.id}
        let categories = []

        if(req.body.categories.includes(',')){
            let str = req.body.categories.replace(/\s+/g, "")
            categories = str.split(',')
        }else{
            categories = [req.body.categories]
        }

        let newvalue = {$set: {
            title: req.body.title,
            content: req.body.content,
            categories: categories,
            thumb: req.body.thumb,
            date: req.body.datetime,
            videos: req.body.videos
        }}
     
        await req.mydb.collection("posts").updateOne(myquery,newvalue)
    }

    async deleteItem(req){
        const myquery = {id:req.params.id}
     
        await req.mydb.collection("posts").deleteOne(myquery)
    }
}

export default new Post()

 

//public/scripts/backend/paginate.js

let page = 0

function paginate(route){
    $('.paginate img').attr('src', '/images/loading.gif')
    page += 1
    
    $.post(`${route}/paginate`,{page:page},function(data, status){
        appendItem(data.items,route,data)
    })
}

function appendItem(items, route,data){
    let html = ''
    
    if(items){
        for(let item of items){
            html += `<li>`
                html += `<div class='thumb'>`
                    html += `<a href="/${data.type}/${item.id}"><img src="${item.thumb}"/></a>`
                    if((item.videos)&&(item.videos !== '[]')&&(item.videos !== '')){
                        html += `<img class="play-icon" src="/images/play.png"/>`
                    }
                html += `</div>`
                html += `<div class="title">`
                    html += `<a href="/${data.type}/${item.id}">${item.title}</a>`
                    html += `<div>${new Date(item.date).toLocaleDateString('it-IT')}</div>`
                html += `</div>`
                html += `<div class="edit">`
                    html += `<a href="${route}/edit/${item.id}"><img src="/images/edit.png"/></a>`
                    html += `<a href="${route}/delete/${item.id}"><img src="/images/delete.png"/></a>`
                html += `</div>` 
            html += `</li>`
        }
    }
    $('.list').append(html)

    if(route === '/admin/user'){
        $('.Listing .list li').css({'grid-template-columns':'13% auto 25%'})
        $('.Listing .list li .thumb').css({'padding-top':'100%'})
        $('.Listing .list li .thumb img').css({'border-radius':'50%'})
    }

    $('.paginate img').attr('src', '/images/load-more.png')
}

 

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

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