//routes/backend/category.js

import express from 'express'
const categoryRouter = express.Router()
import category from '../../controllers/backend/category.js'

categoryRouter.get('/', async function(req,res){
    await category.getPage(req,res)
})

categoryRouter.post('/', async function(req,res){
    await category.createItem(req,res)
})

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

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

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

categoryRouter.post('/paginate', async function(req,res){
    await category.paginateItem(req,res)
})

export default categoryRouter

 

//controllers/backend/category.js

import category from '../../models/category.js'

class Category{
    async getPage(req,res){
        if(req.session.user){
            req.settings.pageTitle = 'ទំព័រ​ជំពូក'
            req.settings.message = ''
            req.settings.route = '/admin/category'
            req.settings.type = "category"

            req.settings.items = await category.getItem(req,req.settings.dItemLimit)
            req.settings.count = await category.countItem(req)

            if(req.params.id){
                req.settings.item = await category.getItem(req,req.settings.dItemLimit,req.params.id)
            }
  
            res.render('base', {data:req.settings})
        }else{
            res.redirect('/admin/login')
        }
    }

    async createItem(req,res){
        if(req.session.user){
            if(req.session.user.role == 'Admin'){
                category.createItem(req)
            }

            res.redirect('/admin/category')
        }else{
            res.redirect('/admin/login')
        }
    }

    async updateItem(req,res){
        if(req.session.user){
            if(req.session.user.role == 'Admin'){
                category.updateItem(req)
            }

            res.redirect('/admin/category')
        }else{
            res.redirect('/admin/login')
        }
    }

    async deleteItem(req,res){
        if(req.session.user){
            if(req.session.user.role == 'Admin'){
                category.deleteItem(req)
            }

            res.redirect('/admin/category')
        }else{
            res.redirect('/admin/login')
        }
    }

    async paginateItem(req,res){
        if(req.session.user){
            req.settings.type = 'category'
            req.settings.items = await category.getItem(req,req.settings.dItemLimit)
            res.json(req.settings)
        }else{
            res.redirect('/admin/login')
        }
    }
}

export default new Category()

 

//models/category.js

class Category{
    async createItem(req){
        const id = Date.now() + Math.round(Math.random() * 1E9).toString()
 
        let myCategory = {
            id: id, 
            title: req.body.label,
            thumb: req.body.thumb,
            date: req.body.datetime
        }
 
        req.mydb.collection("categories").insertOne(myCategory)
    }

    async countItem(req){
        return await req.mydb.collection('categories').countDocuments()
    }

    async getItem(req,amount=10,id=false){
        if(id){
            return await req.mydb.collection("categories").findOne({id:id})
        }else if(req.body.page){
            let page = req.body.page
            return await req.mydb.collection("categories").find().skip(amount*page).sort({date:-1,_id:-1}).limit(amount).toArray()
        }else if(amount === 'all'){
            return await req.mydb.collection("categories").find({}, {title:1,_id:0}).sort({title:1}).toArray()
        }else{
            return await req.mydb.collection("categories").find().sort({date:-1,_id:-1}).limit(amount).toArray()
        }
    }

    async updateItem(req){
        const myquery = {id:req.params.id}
        let newvalue = {$set: {
            title: req.body.label,
            thumb: req.body.thumb,
            date: req.body.datetime
        }}
     
        await req.mydb.collection("categories").updateOne(myquery,newvalue)
    }

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

export default new Category()

 

<!--views/backend/index.ejs-->

<link href="/styles/backend/index.css" rel="stylesheet">
<script src="/scripts/backend/paginate.js"></script>
 
<section class="Header">
    <div class="wrapper region">
        <div class="logo"><%= data.pageTitle %></div>
        <form method="post" action="/search">
            <select name="type">
                <option>ការផ្សាយ</option>
                <option>ទំព័រស្តាទិក</option>
                <option>អ្នក​ប្រើប្រាស់</option>
            </select>
            <input type="text" name="q" placeholder="Search" required>
            <input type="submit" value="ស្វែង​រក">
        </form>
        <div class="logout">
            <a href="/">ទំព័រ​មុខ</a> | <a href="/admin/login/logout">ចេញ​ក្រៅ</a>
        </div>
    </div>
</section>
 
<section class="Body">
    <div class="wrapper region">
        <div class="sidebar">
            <a href='/admin/post'><img src='/images/movie.png' /></a>
            <a href='/admin/post'>ការផ្សាយ</a>
            
            <a href='/admin/category'><img src='/images/category.png' /></a>
            <a href='/admin/category'>ជំពូក</a>
            
            <a href='/admin/book'><img src='/images/books.png' /></a>
            <a href='/admin/book'>សៀវភៅ</a>
            
            <a href='/admin/upload'><img src='/images/upload.png' /></a>
            <a href='/admin/upload'>Upload</a>
            
            <a href='/admin/user'><img src='/images/users.png' /></a>
            <a href='/admin/user'>អ្នក​ប្រើប្រាស់</a>
            
            <a href='/admin/setting'><img src='/images/setting.png' /></a>
            <a href='/admin/setting'>Setting</a>
        </div>
        
        <% if(data.route == '/admin/post'){ %>
            <%- include('./post.ejs') %>
        <% } else if(data.route == '/admin/category'){ %>
            <%- include('./category.ejs') %>
        <% } %>

    </div>
</section>

<section class="Footer Listing region">
    <div class="info">សរុប​ទាំងអស់​មាន​ចំនួនៈ <%= data.count %></div>

    <ul class="list">
        <% if('items' in data){ %>
            <% for(let item of data.items) { %>
            <li>
                <div class='thumb'>
                    <a href='/<%= data.type %>/<%= item.id %>'><img src='<%= item.thumb %>'/></a>
                    <% if('video' in item){ %>
                        <% if(item.video !== ''){ %>
                            <img class="play-icon" src="/images/play-icon"/>
                        <% } %>
                    <% } %>
                </div>
                <div class="title">
                    <a href="/<%= data.type %>/<%= item.id %>"><%= item.title %></a>
                    <div><%= (new Date(item.date)).toLocaleDateString('it-IT') %></div>
                </div>
                <div class="edit">
                    <a href="<%= data.route %>/edit/<%= item.id %>"><img src="/images/edit.png"/></a>
                    <a href="<%= data.route %>/delete/<%= item.id %>"><img src="/images/delete.png"/></a>
                </div> 
            </li>
            <% } %>
        <% } %>
    </ul>

    <div class="paginate">
        <img onclick="paginate('<%= data.route %>')" src='/images/load-more.png' />
    </div>
</section>

 

//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.video)&&(item.video !== '[]')){
                        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()}</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