We already know that we can use different HTTP methods with different handlers for one route to obtain different result according to our need. For example, we can use HTTP GET method with “/users/post” route to show the posting page in the dashboard, and we are going to use HTTP POST method with the same route “/users/post” to create and insert post item into MongoDB database.
As the task to create and insert post into the database is reserved only for registered user, we need to defend this “/users/post” route by checking who is trying to use this route to see if he/she is authenticated or not.
// routes/users/post.js
import { Router } from "../../deps.ts";
const router = new Router();
import post from "../../controllers/users/post.js"
router.get("/", async (req, res) => {
if(await req.mysession.get("user")){
post.getPage(req, res);
}else{
res.redirect("/users");
}
});
router.post("/", async (req, res) => {
if(await req.mysession.get("user")){
post.createPost(req, res);
}else{
res.redirect("/users");
}
})
export default router;
// controllers/users/post.js
import post from "../../views/users/post.jsx";
import postdb from "../../models/post.ts";
class Post{
async getPage(req, res){
const config = req.mysetting();
config.page_title = "Post Page";
config.route = "/users/post";
config.username = (await req.mysession.get("user")).title;
const html = await post(config);
res.send(html);
}
async createPost(req, res){
if((await req.mysession.get("user")).role in {'Admin':1,'Editor':1,'Author':1}){
await postdb.createPost(req);
}
res.redirect("/users/post");
}
}
export default new Post();
// models/post.ts
interface PostSchema {
_id: ObjectId;
id: string;
title: string;
content: string;
categories: string[];
thumb: string;
date: string;
userid: string;
}
class Post{
async count(req, query={}){
const posts = req.mydb.collection<PostSchema>("posts");
return await posts.countDocuments(query);
}
async createPost(req){
const id = crypto.randomUUID();
let categories: string[];
if(req.body.categories.includes(',')){
categories = req.body.categories.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,
userid: (await req.mysession.get("user")).id,
}
const posts = req.mydb.collection<PostSchema>("posts")
await posts.insertOne(new_post)
}
}
export default new Post();
GitHub: https://github.com/Sokhavuth/opine-job
Deno Deploy: https://khmerweb-job.deno.dev/users/post