신선한 블로그 엔진: 게시물 항목 편집/삭제
35213 단어 javascriptreactfreshwebdev
목차
Sokhavuth TIN ・ 8월 9일 ・ 2분 읽기
GitHub: https://github.com/Sokhavuth/deno-fresh
데노 배치: https://khmerweb-fresh.deno.dev/login
// 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} />
)
}
// 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();
// 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()
Reference
이 문제에 관하여(신선한 블로그 엔진: 게시물 항목 편집/삭제), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/sokhavuth/blog-engine-with-fresh-editdelete-post-item-27hn텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)