diff --git a/pages/api/v1/posts/[id].tsx b/pages/api/v1/posts/[id].tsx index 723128e..8cf3df6 100644 --- a/pages/api/v1/posts/[id].tsx +++ b/pages/api/v1/posts/[id].tsx @@ -18,6 +18,12 @@ const Posts: NextApiHandler = withSession(async (req, res) => { } await connection.manager.save(post); res.json(post); + } else if (req.method === 'DELETE') { + const id = req.query.id.toString(); + const connection = await getDatabaseConnection(); + const result = await connection.manager.delete('Post', id); + res.statusCode = result.affected >= 0 ? 200 : 400; + res.end(); } }); diff --git a/pages/posts/[id].tsx b/pages/posts/[id].tsx index fb7faaa..842d48b 100644 --- a/pages/posts/[id].tsx +++ b/pages/posts/[id].tsx @@ -1,25 +1,38 @@ -import React from 'react'; +import React, {useCallback} from 'react'; import {GetServerSideProps, GetServerSidePropsContext, NextPage} from 'next'; import {getDatabaseConnection} from '../../lib/getDatabaseConnection'; import {Post} from '../../src/entity/Post'; import marked from 'marked'; import Link from 'next/link'; import {withSession} from '../../lib/withSession'; +import axios from 'axios'; +import {useRouter} from 'next/router'; type Props = { + id: number; post: Post; currentUser: User | null; } const postsShow: NextPage = (props) => { - const {post, currentUser} = props; + const {post, currentUser, id} = props; + const router = useRouter() + const onRemove = useCallback(() => { + axios.delete(`/api/v1/posts/${id}`).then(() => { + window.alert('删除成功'); + router.push('/posts') + }, () => { + window.alert('删除失败'); + }); + }, [id]); return ( <>

{post.title}

{currentUser && -

+

编辑 +

}
@@ -27,12 +40,19 @@ const postsShow: NextPage = (props) => {
); @@ -41,14 +61,16 @@ const postsShow: NextPage = (props) => { export default postsShow; export const getServerSideProps: GetServerSideProps = withSession( -async (context: GetServerSidePropsContext) => { - const connection = await getDatabaseConnection(); - const post = await connection.manager.findOne('Post', context.params.id); - const currentUser = (context.req as any).session.get('currentUser') || null; - return { - props: { - post: JSON.parse(JSON.stringify(post)), - currentUser - } - }; -}); \ No newline at end of file + async (context: GetServerSidePropsContext) => { + const connection = await getDatabaseConnection(); + const id = context.params.id; + const post = await connection.manager.findOne('Post', id); + const currentUser = (context.req as any).session.get('currentUser') || null; + return { + props: { + id: parseInt(id.toString()), + post: JSON.parse(JSON.stringify(post)), + currentUser + } + }; + }); \ No newline at end of file