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

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

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

export default new Category()

 

//models/category.js

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

export default new Category()

 

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

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