Blog Engine with Fresh: Edit/Delete Post Item
Tags: javascript, webdev, react, fresh
Published: 2022-08-09 10:55:00

{% embed https://dev.to/sokhavuth/table-of-contents-41pd %}
GitHub: [https://github.com/Sokhavuth/deno-fresh](https://github.com/Sokhavuth/deno-fresh)
Deno Deploy: [https://khmerweb-fresh.deno.dev/login](https://khmerweb-fresh.deno.dev/login)
<br/>

```js
// routes/admin/post/[name]/[id].jsx

/** @jsx h */
import { h } from "preact";
import VPost from '../../../../components/admin/post.jsx';
import CPost from "../../../../controllers/admin/post_edit_delete.js";


export const handler = {
    async GET(req, ctx){
        return await CPost.editDeletePost(req, ctx);
    },


    async POST(req, ctx) {
        return await CPost.updatePost(req, ctx);
    },
}


export default function Template(props) {
    return (
        <VPost data={props.data} />
    )
}
```

```js
// controllers/admin/post_edit_delete.js

import { getCookies, deleteCookie } from "cookies";
import { setting, secret_key, myredis } from 'setting';
import { verify } from "jwt";
import postdb from "../../models/post.ts";


class PostEditDelete{
    async editDeletePost(req, ctx){
        const cookies = getCookies(req.headers);
        if((cookies)&&(cookies.session_id)){
            const jwt = await myredis.get(cookies.session_id);
            try{
                const payload = await verify(jwt, secret_key, "HS512")
                if(payload.user){
                    const config = setting();
                    config.page_title = "កែប្រែ​ការផ្សាយ";
                    config.username = payload.user.title;
                    config.count = await postdb.count();
                
                    if(ctx.params.name === 'edit'){
                        config.item = await postdb.getPost(ctx.params.id);
                    }else if(ctx.params.name === 'delete'){
                        const post = await postdb.getPost(ctx.params.id);
                        if((payload.user.role in {'Admin':1})||(payload.user.id === post.userid)){
                            await postdb.deletePost(ctx.params.id);
                        }
                        return new Response(undefined, { headers: {location: `/admin/post`}, status: 302 });
                    }else{
                        console.log('');
                    }
                    
                    config.items = await postdb.getPosts(config.post_amount);

                    return await ctx.render({"setting": config});
                }
            }catch(error){
                console.log(error)
                const resp = new Response(undefined, { headers: {location: `/login`}, status: 302 });
                deleteCookie(resp.headers, "session_id");
                return resp;
            }
        }

        return new Response(undefined, { headers: {location: `/login`}, status: 302 });
    }

    async updatePost(req, ctx){
        const cookies = getCookies(req.headers);
        if((cookies)&&(cookies.session_id)){
            const jwt = await myredis.get(cookies.session_id);
            try{
                const payload = await verify(jwt, secret_key, "HS512");
                const post = await postdb.getPost(ctx.params.id);
                if((post.userid === payload.user.id)||(payload.user.role in {'Admin':1,'Editor':1})){
                    if(ctx.params.name === 'edit'){
                        await postdb.updatePost(req, ctx.params.id);
                    }
                    return new Response(undefined, { headers: {location: `/admin/post`}, status: 302 });
                }
            }catch(error){
                console.log(error);
                const resp = new Response(undefined, { headers: {location: `/login`}, status: 302 });
                deleteCookie(resp.headers, "session_id");
                return resp;
            }
        }

        return new Response(undefined, { headers: {location: `/login`}, status: 302 });
    }
}

export default new PostEditDelete();
```

```js
// models/post.ts

import { mydb } from "setting"

interface PostSchema {
    _id: ObjectId;
    id: string; 
    title: string;
    content: string;
    categories: string[];
    thumb: string;
    date: string;
    videos: string;
    userid: string;
}

class Post{
    async count(query={}){
        const posts = mydb.collection<PostSchema>("posts")
        return await posts.countDocuments(query)
    }

    async insertPost(req, user_id: string){
        const id = crypto.randomUUID()
        const formData = await req.formData()

        let categories: string[]

        if(formData.get("categories").includes(',')){
            categories = formData.get("categories").split(',')
        }else{
            categories = [formData.get("categories")]
        }
        
        const new_post = {
            id: id, 
            title: formData.get("title"),
            content: formData.get("content"),
            categories: categories,
            thumb: formData.get("thumb"),
            date: formData.get("datetime"),
            videos: formData.get("videos"),
            userid: user_id,
        }
 
        const posts = mydb.collection<PostSchema>("posts")
        await posts.insertOne(new_post)
    }

    async getPosts(amount: number, query={}){
        const posts = mydb.collection<PostSchema>("posts")
        return await posts.find(query).sort({date:-1,_id:-1}).limit(amount).toArray()
    }

    async getPost(post_id: string){
        const posts = mydb.collection<PostSchema>("posts")
        return await posts.findOne({id: post_id})
    }

    async updatePost(req, post_id: string){
        const formData = await req.formData()

        let categories: string[]

        if(formData.get("categories").includes(',')){
            categories = formData.get("categories").split(',')
        }else{
            categories = [formData.get("categories")]
        }

        const edited_post = {$set:{
            title: formData.get("title"),
            content: formData.get("content"),
            categories: categories,
            thumb: formData.get("thumb"),
            date: formData.get("datetime"),
            videos: formData.get("videos"),
        }}

        const posts = mydb.collection<PostSchema>("posts")
        await posts.updateOne({id: post_id}, edited_post)
    }

    async deletePost(post_id: string){
        const posts = mydb.collection<PostSchema>("posts")
        await posts.deleteOne({id: post_id})
    }

}

export default new Post()
```