-
Notifications
You must be signed in to change notification settings - Fork 0
/
[id].tsx
76 lines (73 loc) · 2.47 KB
/
[id].tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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> = (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 (
<>
<div className="wrapper">
<header>
<h1>{post.title}</h1>
{currentUser &&
<p className="actions">
<Link href="/posts/[id]/edit" as={`/posts/${post.id}/edit`}><a>编辑</a></Link>
<button className="deleteButton" onClick={onRemove}>删除</button>
</p>
}
</header>
<article className="markdown-body" dangerouslySetInnerHTML={{__html: marked(post.content)}}>
</article>
</div>
<style jsx>{`
.actions > *{
margin: 4px;
}
.actions > *:first-child{
margin-left: 0;
}
.wrapper{
max-width: 800px;
margin: 16px auto;
padding: 0 16px;
}
h1{padding-bottom: 16px; border-bottom: 1px solid #666;}
.deleteButton{color:red;background:transparent;border:none;}
`}</style>
</>
);
};
export default postsShow;
export const getServerSideProps: GetServerSideProps<any, { id: string }> = withSession(
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
}
};
});