You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.2 KiB
92 lines
2.2 KiB
import React from "react";
|
|
import { GetServerSideProps } from "next";
|
|
import ReactMarkdown from "react-markdown";
|
|
import Layout from "../../components/Layout";
|
|
import Router from "next/router";
|
|
import { PostProps } from "../../components/Post";
|
|
import prisma from '../../lib/prisma'
|
|
import { useSession } from "next-auth/react";
|
|
|
|
|
|
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
|
|
const post = await prisma.post.findUnique({
|
|
where: {
|
|
id: Number(params?.id) || -1,
|
|
},
|
|
include: {
|
|
author: {
|
|
select: { name: true, email: true },
|
|
},
|
|
},
|
|
});
|
|
return {
|
|
props: post,
|
|
};
|
|
};
|
|
|
|
async function publishPost(id: number): Promise<void> {
|
|
await fetch(`/api/publish/${id}`, {
|
|
method: "PUT",
|
|
});
|
|
await Router.push("/")
|
|
}
|
|
|
|
async function deletePost(id: number): Promise<void> {
|
|
await fetch(`/api/post/${id}`, {
|
|
method: "DELETE",
|
|
});
|
|
await Router.push("/")
|
|
}
|
|
|
|
const Post = (props : PostProps) => {
|
|
const { data: session, status } = useSession();
|
|
if (status === 'loading') {
|
|
return <div>Authenticating ...</div>;
|
|
}
|
|
const userHasValidSession = Boolean(session);
|
|
const postBelongsToUser = session?.user?.email === props.author?.email;
|
|
let title = props.title;
|
|
if (!props.published) {
|
|
title = `${title} (Draft)`;
|
|
}
|
|
|
|
return (
|
|
<Layout>
|
|
<div>
|
|
<h2>{title}</h2>
|
|
<p>By {props?.author?.name || "Unknown author"}</p>
|
|
<ReactMarkdown children={props.content} />
|
|
{!props.published && userHasValidSession && postBelongsToUser && (
|
|
<button onClick={() => publishPost(props.id)}>Publish</button>
|
|
)}
|
|
{userHasValidSession && postBelongsToUser && (
|
|
<button onClick={() => deletePost(props.id)}>Delete</button>
|
|
)}
|
|
</div>
|
|
<style jsx>{`
|
|
.page {
|
|
background: white;
|
|
padding: 2rem;
|
|
}
|
|
|
|
.actions {
|
|
margin-top: 2rem;
|
|
}
|
|
|
|
button {
|
|
background: #ececec;
|
|
border: 0;
|
|
border-radius: 0.125rem;
|
|
padding: 1rem 2rem;
|
|
}
|
|
|
|
button + button {
|
|
margin-left: 1rem;
|
|
}
|
|
`}</style>
|
|
</Layout>
|
|
);
|
|
};
|
|
|
|
export default Post;
|