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

postRouter.get('/edit/:id',async (req,res)=>{
    if(req.session.user){
        post.editItem(req,res)
    }else{
        res.redirect('/login')
    }
})

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

postRouter.get('/delete/:id',async (req,res)=>{
    if(req.session.user){
        post.deleteItem(req,res)
    }else{
        res.redirect('/login')
    }
})

postRouter.post('/paginate',async (req,res)=>{
    if(req.session.user){
        post.paginateItem(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')
    }

    async editItem(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.item = await postdb.editItem(req)
        this.config.items = await postdb.getItem(req,this.config.maxPosts)

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

    async updateItem(req,res){
        let item = await postdb.editItem(req)
        if((req.session.user.role === 'Admin')||(req.session.user.id === item.userid)){
            await postdb.updateItem(req)
        }

        res.redirect('/admin/post')
    }

    async deleteItem(req,res){
        let item = await postdb.editItem(req)
        if((req.session.user.role === 'Admin')||(req.session.user.id === item.userid)){
            await postdb.deleteItem(req)
        }

        res.redirect('/admin/post')
    }

    async paginateItem(req,res){
        this.config = await config()
        this.config.route = '/admin/post'
        this.config.type = 'post'

        this.config.items = await postdb.paginateItem(req,this.config.maxPosts)

        res.json(this.config)
    }
}

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

    async editItem(req){
        return await req.mydb.collection('posts').findOne({id:req.params.id})
    }

    async updateItem(req){
        let myquery = {id: req.params.id}

        if(req.body.categories.includes(',')){
            var categories = req.body.categories.split(',')
        }else{
            var categories = [req.body.categories]
        }

        let newvalue = {$set: {
            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
        }}
 
        await req.mydb.collection("posts").updateOne(myquery,newvalue)
    }

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

    async paginateItem(req,amount){
        const page = req.body.page
        return await req.mydb.collection("posts").find().skip(amount*page).sort({date:-1,_id:-1}).limit(amount).toArray()
    }
}

export default new Post()

 

//static/scripts/paginate.js

let page = 0

function paginate(route){
    $('.pagination 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}"/>`
                                if((item.video)&&(item.video !== '[]')){
                                    html += `<img class="play-icon" src="/images/play.png"/>`
                                }
                    html += `</a>`
                html += `</div>`
                html += `<div class="title">`
                    html += `<a href="/${data.type}/${item.id}">${item.title}</a>`
                    html += `<div>${new Date(item.postdate).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'){
        $('.Footer .list li').css({'grid-template-columns':'13% auto 25%'})
        $('.Footer .list li .thumb').css({'padding-top':'100%'})
        $('.Footer .list li .thumb img').css({'border-radius':'50%'})
    }

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

 

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