Skip to content

Commit

Permalink
complete up to creating and showing a draft
Browse files Browse the repository at this point in the history
  • Loading branch information
dyor committed Dec 27, 2023
1 parent 9d6e678 commit a31a53a
Show file tree
Hide file tree
Showing 7 changed files with 296 additions and 35 deletions.
21 changes: 21 additions & 0 deletions .vscode/launch.json
@@ -0,0 +1,21 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/pages/api/post/index.ts",
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}
52 changes: 26 additions & 26 deletions components/Header.tsx
@@ -1,19 +1,19 @@
import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { signOut, useSession } from 'next-auth/react';
import React from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import { signOut, useSession } from "next-auth/react";

const Header: React.FC = () => {
const router = useRouter();
const isActive: (pathname: string) => boolean = (pathname) =>
router.pathname === pathname;

const { data: session, status } = useSession();
const {data: session, status} = useSession();

let left = (
<div className="left">
<Link legacyBehavior href="/">
<a className="bold" data-active={isActive('/')}>
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
Expand All @@ -24,11 +24,11 @@ const Header: React.FC = () => {
a {
text-decoration: none;
color: var(--geist-foreground);
color: #000;
display: inline-block;
}
.left a[data-active='true'] {
.left a[data-active="true"] {
color: gray;
}
Expand All @@ -44,8 +44,8 @@ const Header: React.FC = () => {
if (status === 'loading') {
left = (
<div className="left">
<Link legacyBehavior href="/">
<a className="bold" data-active={isActive('/')}>
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
Expand All @@ -56,11 +56,11 @@ const Header: React.FC = () => {
a {
text-decoration: none;
color: var(--geist-foreground);
color: #000;
display: inline-block;
}
.left a[data-active='true'] {
.left a[data-active="true"] {
color: gray;
}
Expand All @@ -85,13 +85,13 @@ const Header: React.FC = () => {
if (!session) {
right = (
<div className="right">
<Link legacyBehavior href="/api/auth/signin">
<a data-active={isActive('/signup')}>Log in</a>
<Link href="/api/auth/signin" legacyBehavior>
<a data-active={isActive("/signup")}>Log in</a>
</Link>
<style jsx>{`
a {
text-decoration: none;
color: var(--geist-foreground);
color: #000;
display: inline-block;
}
Expand All @@ -104,7 +104,7 @@ const Header: React.FC = () => {
}
.right a {
border: 1px solid var(--geist-foreground);
border: 1px solid black;
padding: 0.5rem 1rem;
border-radius: 3px;
}
Expand All @@ -116,13 +116,13 @@ const Header: React.FC = () => {
if (session) {
left = (
<div className="left">
<Link legacyBehavior href="/">
<a className="bold" data-active={isActive('/')}>
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
<Link legacyBehavior href="/drafts">
<a data-active={isActive('/drafts')}>My drafts</a>
<Link href="/drafts" legacyBehavior>
<a data-active={isActive("/drafts")}>My drafts</a>
</Link>
<style jsx>{`
.bold {
Expand All @@ -131,11 +131,11 @@ const Header: React.FC = () => {
a {
text-decoration: none;
color: var(--geist-foreground);
color: #000;
display: inline-block;
}
.left a[data-active='true'] {
.left a[data-active="true"] {
color: gray;
}
Expand All @@ -150,7 +150,7 @@ const Header: React.FC = () => {
<p>
{session.user.name} ({session.user.email})
</p>
<Link legacyBehavior href="/create">
<Link href="/create" legacyBehavior>
<button>
<a>New post</a>
</button>
Expand All @@ -161,7 +161,7 @@ const Header: React.FC = () => {
<style jsx>{`
a {
text-decoration: none;
color: var(--geist-foreground);
color: #000;
display: inline-block;
}
Expand All @@ -180,7 +180,7 @@ const Header: React.FC = () => {
}
.right a {
border: 1px solid var(--geist-foreground);
border: 1px solid black;
padding: 0.5rem 1rem;
border-radius: 3px;
}
Expand Down
19 changes: 19 additions & 0 deletions pages/api/auth/[...nextauth].ts
@@ -0,0 +1,19 @@
import { NextApiHandler } from "next";
import NextAuth from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import GitHubProvider from "next-auth/providers/github";
import prisma from "../../../lib/prisma";

export const options = { // <--- exported the nextauth options
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.SECRET,
};

const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;
21 changes: 21 additions & 0 deletions pages/api/post/index.ts
@@ -0,0 +1,21 @@
import { getServerSession } from "next-auth/next" // <--- imported getServerSession from "next-auth/next"
import { options as authOptions } from "../auth/[...nextauth]" // <--- imported authOptions
import prisma from "../../../lib/prisma";

// POST /api/post
// Required fields in body: title
// Optional fields in body: content
export default async function handle(req, res) {
const { title, content } = req.body;

// const session = await getSession({ req }); // <--- removed getSession call
const session = await getServerSession(req, res, authOptions); // <--- used the getServerSession instead
const result = await prisma.post.create({
data: {
title: title,
content: content,
author: { connect: { email: session?.user?.email } },
},
});
res.json(result);
}
81 changes: 81 additions & 0 deletions pages/create.tsx
@@ -0,0 +1,81 @@
import React, { useState } from 'react';
import Layout from '../components/Layout';
import Router from 'next/router';

const Draft: React.FC = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');

const submitData = async (e: React.SyntheticEvent) => {
e.preventDefault();
try {
const body = { title, content };
await fetch('/api/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
await Router.push('/drafts');
} catch (error) {
console.error(error);
}
};

return (
<Layout>
<div>
<form onSubmit={submitData}>
<h1>New Draft</h1>
<input
autoFocus
onChange={(e) => setTitle(e.target.value)}
placeholder="Title"
type="text"
value={title}
/>
<textarea
cols={50}
onChange={(e) => setContent(e.target.value)}
placeholder="Content"
rows={8}
value={content}
/>
<input disabled={!content || !title} type="submit" value="Create" />
<a className="back" href="#" onClick={() => Router.push('/')}>
or Cancel
</a>
</form>
</div>
<style jsx>{`
.page {
background: var(--geist-background);
padding: 3rem;
display: flex;
justify-content: center;
align-items: center;
}
input[type='text'],
textarea {
width: 100%;
padding: 0.5rem;
margin: 0.5rem 0;
border-radius: 0.25rem;
border: 0.125rem solid rgba(0, 0, 0, 0.2);
}
input[type='submit'] {
background: #ececec;
border: 0;
padding: 1rem 2rem;
}
.back {
margin-left: 1rem;
}
`}</style>
</Layout>
);
};

export default Draft;
77 changes: 77 additions & 0 deletions pages/drafts.tsx
@@ -0,0 +1,77 @@
import React from 'react';
import { GetServerSideProps } from 'next';
import { useSession, getSession } from 'next-auth/react';
import Layout from '../components/Layout';
import Post, { PostProps } from '../components/Post';
import prisma from '../lib/prisma';

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
const session = await getSession({ req });
if (!session) {
res.statusCode = 403;
return { props: { drafts: [] } };
}

const drafts = await prisma.post.findMany({
where: {
author: { email: session.user.email },
published: false,
},
include: {
author: {
select: { name: true },
},
},
});
return {
props: { drafts },
};
};

type Props = {
drafts: PostProps[];
};

const Drafts: React.FC<Props> = (props) => {
const { data: session } = useSession();

if (!session) {
return (
<Layout>
<h1>My Drafts</h1>
<div>You need to be authenticated to view this page.</div>
</Layout>
);
}

return (
<Layout>
<div className="page">
<h1>My Drafts</h1>
<main>
{props.drafts.map((post) => (
<div key={post.id} className="post">
<Post post={post} />
</div>
))}
</main>
</div>
<style jsx>{`
.post {
background: var(--geist-background);
transition: box-shadow 0.1s ease-in;
}
.post:hover {
box-shadow: 1px 1px 3px #aaa;
}
.post + .post {
margin-top: 2rem;
}
`}</style>
</Layout>
);
};

export default Drafts;

0 comments on commit a31a53a

Please sign in to comment.