first commit

feature/page-admin
Eric 4 years ago
commit 6857e301fa

13
.env

@ -0,0 +1,13 @@
SECRET=RANDOM_STRING
NEXTAUTH_URL='http://localhost:3000'
# GitHub oAuth
GITHUB_ID=YOUR_GITHUB_CLIENT_ID
GITHUB_SECRET=YOUR_GITHUB_CLIENT_SECRET
# Email (magic link)
SMTP_HOST=YOUR_SMTP_HOST
SMTP_PORT=YOUR_SMTP_PORT
SMTP_USER=YOUR_SMTP_USERNAME
SMTP_PASSWORD=YOUR_SMTP_PASSWORD
SMTP_FROM=YOUR_REPLY_TO_EMAIL_ADDRESS

2
.gitignore vendored

@ -0,0 +1,2 @@
node_modules/
.next/

@ -0,0 +1,7 @@
{
"workbench.colorCustomizations": {
"activityBar.background": "#521342",
"titleBar.activeBackground": "#731B5D",
"titleBar.activeForeground": "#FDF8FC"
}
}

@ -0,0 +1,284 @@
# Fullstack Authentication Example with Next.js and NextAuth.js
This example shows how to implement a **fullstack app in TypeScript with [Next.js](https://nextjs.org/)** using [React](https://reactjs.org/) (frontend), [Next.js API routes](https://nextjs.org/docs/api-routes/introduction) and [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client) (backend). It also demonstrates how to implement authentication using [NextAuth.js](https://next-auth.js.org/). The example uses an SQLite database file with some initial dummy data which you can find at [`./prisma/dev.db`](./prisma/dev.db).
Note that the app uses a mix of server-side rendering with `getServerSideProps` (SSR) and static site generation with `getStaticProps` (SSG). When possible, SSG is used to make database queries already at build-time (e.g. when fetching the [public feed](./pages/index.tsx)). Sometimes, the user requesting data needs to be authenticated, so SSR is being used to render data dynamically on the server-side (e.g. when viewing a user's [drafts](./pages/drafts.tsx)).
## Getting started
### 1. Download example and install dependencies
Download this example:
```
curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/typescript/rest-nextjs-api-routes-auth
```
Install npm dependencies:
```
cd rest-nextjs-api-routes-auth
npm install
```
<details><summary><strong>Alternative:</strong> Clone the entire repo</summary>
Clone this repository:
```
git clone git@github.com:prisma/prisma-examples.git --depth=1
```
Install npm dependencies:
```
cd prisma-examples/typescript/rest-nextjs-api-routes-auth
npm install
```
</details>
### 2. Create and seed the database
Run the following command to create your SQLite database file. This also creates the `User` and `Post` tables that are defined in [`prisma/schema.prisma`](./prisma/schema.prisma):
```
npx prisma migrate dev --name init
```
When `npx prisma migrate dev` is executed against a newly created database, seeding is also triggered. The seed file in [`prisma/seed.ts`](./prisma/seed.ts) will be executed and your database will be populated with the sample data.
### 3. Configuring your authentication provider
In order to get this example to work, you need to configure the [GitHub](https://next-auth.js.org/providers/github) and/or [Email](https://next-auth.js.org/providers/email) authentication providers from NextAuth.js.
#### Configuring the GitHub authentication provider
<details><summary>Expand to learn how you can configure the GitHub authentication provider</summary>
First, log into your [GitHub](https://github.com/) account.
Then, navigate to [**Settings**](https://github.com/settings/profile), then open to [**Developer Settings**](https://github.com/settings/apps), then switch to [**OAuth Apps**](https://github.com/settings/developers).
![](https://res.cloudinary.com/practicaldev/image/fetch/s--fBiGBXbE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/4eQrMAs.png)
Clicking on the **Register a new application** button will redirect you to a registration form to fill out some information for your app. The **Authorization callback URL** should be the Next.js `/api/auth` route.
An important thing to note here is that the **Authorization callback URL** field only supports a single URL, unlike e.g. Auth0, which allows you to add additional callback URLs separated with a comma. This means if you want to deploy your app later with a production URL, you will need to set up a new GitHub OAuth app.
![](https://res.cloudinary.com/practicaldev/image/fetch/s--v7s0OEs_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/tYtq5fd.png)
Click on the **Register application** button, and then you will be able to find your newly generated **Client ID** and **Client Secret**. Copy and paste this info into the [`.env`](./env) file in the root directory.
The resulting section in the `.env` file might look like this:
```
# GitHub oAuth
GITHUB_ID=6bafeb321963449bdf51
GITHUB_SECRET=509298c32faa283f28679ad6de6f86b2472e1bff
```
</details>
#### Configuring the Email authentication provider
You can [follow the instructions in the NextAuth.js documentation](https://next-auth.js.org/providers/email#configuration) to configure the Email authentication provider. Once your email authentication provider is configured, you can set the environment variables in [`.env`](./env) accordingly.
### 4. Start the app
```
npm run dev
```
The app is now running, navigate to [`http://localhost:3000/`](http://localhost:3000/) in your browser to explore its UI.
## Evolving the app
Evolving the application typically requires three steps:
1. Migrate your database using Prisma Migrate
1. Update your server-side application code
1. Build new UI features in React
For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.
### 1. Migrate your database using Prisma Migrate
The first step is to add a new table, e.g. called `Profile`, to the database. You can do this by adding a new model to your [Prisma schema file](./prisma/schema.prisma) file and then running a migration afterwards:
```diff
// schema.prisma
model Post {
id Int @default(autoincrement()) @id
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int
}
model User {
id Int @default(autoincrement()) @id
name String?
email String @unique
posts Post[]
+ profile Profile?
}
+model Profile {
+ id Int @default(autoincrement()) @id
+ bio String?
+ userId Int @unique
+ user User @relation(fields: [userId], references: [id])
+}
```
Once you've updated your data model, you can execute the changes against your database with the following command:
```
npx prisma migrate dev
```
### 2. Update your application code
You can now use your `PrismaClient` instance to perform operations against the new `Profile` table. Here are some examples:
#### Create a new profile for an existing user
```ts
const profile = await prisma.profile.create({
data: {
bio: "Hello World",
user: {
connect: { email: "alice@prisma.io" },
},
},
});
```
#### Create a new user with a new profile
```ts
const user = await prisma.user.create({
data: {
email: "john@prisma.io",
name: "John",
profile: {
create: {
bio: "Hello World",
},
},
},
});
```
#### Update the profile of an existing user
```ts
const userWithUpdatedProfile = await prisma.user.update({
where: { email: "alice@prisma.io" },
data: {
profile: {
update: {
bio: "Hello Friends",
},
},
},
});
```
### 3. Build new UI features in React
Once you have added a new endpoint to the API (e.g. `/api/profile` with `/POST`, `/PUT` and `GET` operations), you can start building a new UI component in React. It could e.g. be called `profile.tsx` and would be located in the `pages` directory.
In the application code, you can access the new endpoint via `fetch` operations and populate the UI with the data you receive from the API calls.
## Switch to another database (e.g. PostgreSQL, MySQL, SQL Server, MongoDB)
If you want to try this example with another database than SQLite, you can adjust the the database connection in [`prisma/schema.prisma`](./prisma/schema.prisma) by reconfiguring the `datasource` block.
Learn more about the different connection configurations in the [docs](https://www.prisma.io/docs/reference/database-reference/connection-urls).
<details><summary>Expand for an overview of example configurations with different databases</summary>
### PostgreSQL
For PostgreSQL, the connection URL has the following structure:
```prisma
datasource db {
provider = "postgresql"
url = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
}
```
Here is an example connection string with a local PostgreSQL database:
```prisma
datasource db {
provider = "postgresql"
url = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
}
```
### MySQL
For MySQL, the connection URL has the following structure:
```prisma
datasource db {
provider = "mysql"
url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
}
```
Here is an example connection string with a local MySQL database:
```prisma
datasource db {
provider = "mysql"
url = "mysql://janedoe:mypassword@localhost:3306/notesapi"
}
```
### Microsoft SQL Server
Here is an example connection string with a local Microsoft SQL Server database:
```prisma
datasource db {
provider = "sqlserver"
url = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
}
```
### MongoDB
Here is an example connection string with a local MongoDB database:
```prisma
datasource db {
provider = "mongodb"
url = "mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin&retryWrites=true&w=majority"
}
```
Because MongoDB is currently in [Preview](https://www.prisma.io/docs/about/releases#preview), you need to specify the `previewFeatures` on your `generator` block:
```
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongodb"]
}
```
</details>
## Next steps
- Check out the [Prisma docs](https://www.prisma.io/docs)
- Share your feedback in the [`prisma2`](https://prisma.slack.com/messages/CKQTGR6T0/) channel on the [Prisma Slack](https://slack.prisma.io/)
- Create issues and ask questions on [GitHub](https://github.com/prisma/prisma/)
- Watch our biweekly "What's new in Prisma" livestreams on [Youtube](https://www.youtube.com/channel/UCptAHlN1gdwD89tFM3ENb6w)

@ -0,0 +1,211 @@
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();
let left = (
<div className="left">
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
<style jsx>{`
.bold {
font-weight: bold;
}
a {
text-decoration: none;
color: #000;
display: inline-block;
}
.left a[data-active="true"] {
color: gray;
}
a + a {
margin-left: 1rem;
}
`}</style>
</div>
);
let right = null;
if (status === 'loading') {
left = (
<div className="left">
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
<style jsx>{`
.bold {
font-weight: bold;
}
a {
text-decoration: none;
color: #000;
display: inline-block;
}
.left a[data-active="true"] {
color: gray;
}
a + a {
margin-left: 1rem;
}
`}</style>
</div>
);
right = (
<div className="right">
<p>Validating session ...</p>
<style jsx>{`
.right {
margin-left: auto;
}
`}</style>
</div>
);
}
if (!session) {
right = (
<div className="right">
<Link href="/api/auth/signin" legacyBehavior>
<a data-active={isActive("/signup")}>Log in</a>
</Link>
<style jsx>{`
a {
text-decoration: none;
color: #000;
display: inline-block;
}
a + a {
margin-left: 1rem;
}
.right {
margin-left: auto;
}
.right a {
border: 1px solid black;
padding: 0.5rem 1rem;
border-radius: 3px;
}
`}</style>
</div>
);
}
if (session) {
left = (
<div className="left">
<Link href="/" legacyBehavior>
<a className="bold" data-active={isActive("/")}>
Feed
</a>
</Link>
<Link href="/drafts" legacyBehavior>
<a data-active={isActive("/drafts")}>My drafts</a>
</Link>
<style jsx>{`
.bold {
font-weight: bold;
}
a {
text-decoration: none;
color: #000;
display: inline-block;
}
.left a[data-active="true"] {
color: gray;
}
a + a {
margin-left: 1rem;
}
`}</style>
</div>
);
right = (
<div className="right">
<p>
{session.user.name} ({session.user.email})
</p>
<Link href="/create" legacyBehavior>
<button>
<a>New post</a>
</button>
</Link>
<button onClick={() => signOut()}>
<a>Log out</a>
</button>
<style jsx>{`
a {
text-decoration: none;
color: #000;
display: inline-block;
}
p {
display: inline-block;
font-size: 13px;
padding-right: 1rem;
}
a + a {
margin-left: 1rem;
}
.right {
margin-left: auto;
}
.right a {
border: 1px solid black;
padding: 0.5rem 1rem;
border-radius: 3px;
}
button {
border: none;
}
`}</style>
</div>
);
}
return (
<nav>
{left}
{right}
<style jsx>{`
nav {
display: flex;
padding: 2rem;
align-items: center;
}
`}</style>
</nav>
);
};
export default Header;

@ -0,0 +1,50 @@
import React, { ReactNode } from "react";
import Header from "./Header";
type Props = {
children: ReactNode;
};
const Layout: React.FC<Props> = (props) => (
<div>
<Header />
<div className="layout">{props.children}</div>
<style jsx global>{`
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
font-size: 16px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
background: rgba(0, 0, 0, 0.05);
}
input,
textarea {
font-size: 16px;
}
button {
cursor: pointer;
}
`}</style>
<style jsx>{`
.layout {
padding: 0 2rem;
}
`}</style>
</div>
);
export default Layout;

@ -0,0 +1,33 @@
import React from "react";
import Router from "next/router";
import ReactMarkdown from "react-markdown";
export type PostProps = {
id: number;
title: string;
author: {
name: string;
email: string;
} | null;
content: string;
published: boolean;
};
const Post: React.FC<{ post: PostProps }> = ({ post }) => {
const authorName = post.author ? post.author.name : "Unknown author";
return (
<div onClick={() => Router.push("/p/[id]", `/p/${post.id}`)}>
<h2>{post.title}</h2>
<small>By {authorName}</small>
<ReactMarkdown children={post.content} />
<style jsx>{`
div {
color: inherit;
padding: 2rem;
}
`}</style>
</div>
);
};
export default Post;

@ -0,0 +1,20 @@
import { PrismaClient } from "@prisma/client";
declare let global: { prisma: PrismaClient };
// PrismaClient is attached to the `global` object in development to prevent
// exhausting your database connection limit.
//
// Learn more:
// https://pris.ly/d/help/next-js-best-practices
let prisma: PrismaClient
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma

6
next-env.d.ts vendored

@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

4238
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,33 @@
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"keywords": [],
"license": "MIT",
"author": "",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@next-auth/prisma-adapter": "1.0.5",
"@prisma/client": "4.6.0",
"next": "13.0.2",
"next-auth": "4.16.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-markdown": "8.0.3"
},
"devDependencies": {
"@types/next-auth": "3.13.0",
"@types/node": "18.11.9",
"@types/react": "18.0.25",
"prisma": "4.6.0",
"ts-node": "10.9.1",
"typescript": "4.8.4"
},
"prisma": {
"seed": "ts-node prisma/seed.ts"
}
}

@ -0,0 +1,12 @@
import { SessionProvider } from "next-auth/react";
import { AppProps } from "next/app";
const App = ({ Component, pageProps }: AppProps) => {
return (
<SessionProvider session={pageProps.session}>
<Component {...pageProps} />
</SessionProvider>
);
};
export default App;

@ -0,0 +1,33 @@
import { NextApiHandler } from "next";
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import { PrismaAdapter } from '@next-auth/prisma-adapter'
import GitHubProvider from 'next-auth/providers/github'
import EmailProvider from 'next-auth/providers/email'
import prisma from '../../../lib/prisma'
const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;
const options = {
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
EmailProvider({
server: {
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
from: process.env.SMTP_FROM,
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.SECRET,
};

@ -0,0 +1,26 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/react';
import prisma from '../../../lib/prisma'
// DELETE /api/post/:id
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const postId = req.query.id;
const session = await getSession({ req })
if (req.method === "DELETE") {
if (session) {
const post = await prisma.post.delete({
where: { id: Number(postId) },
});
res.json(post);
} else {
res.status(401).send({ message: 'Unauthorized' })
}
} else {
throw new Error(
`The HTTP ${req.method} method is not supported at this route.`
);
}
}

@ -0,0 +1,25 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import prisma from '../../../lib/prisma'
import { getSession } from 'next-auth/react'
// POST /api/post
// Required fields in body: title
// Optional fields in body: content
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const { title, content } = req.body;
const session = await getSession({ req });
if (session) {
const result = await prisma.post.create({
data: {
title: title,
content: content,
author: { connect: { email: session?.user?.email } },
},
});
res.json(result);
} else {
res.status(401).send({ message: 'Unauthorized' })
}
}

@ -0,0 +1,19 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/react';
import prisma from '../../../lib/prisma'
// PUT /api/publish/:id
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const postId = req.query.id;
const session = await getSession({ req })
if (session) {
const post = await prisma.post.update({
where: { id: Number(postId) },
data: { published: true },
});
res.json(post);
} else {
res.status(401).send({ message: 'Unauthorized' })
}
}

@ -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: white;
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;

@ -0,0 +1,78 @@
import React from "react";
import { GetServerSideProps } from "next";
import Layout from "../components/Layout";
import Post, { PostProps } from "../components/Post";
import { useSession, getSession } from "next-auth/react";
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: white;
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,0 +1,60 @@
import React from "react";
import type { GetServerSideProps } from "next";
import Layout from "../components/Layout";
import Post, { PostProps } from "../components/Post";
import prisma from '../lib/prisma'
export const getServerSideProps: GetServerSideProps = async () => {
const feed = await prisma.post.findMany({
where: {
published: true,
},
include: {
author: {
select: {
name: true,
},
},
},
});
return {
props: { feed },
};
};
type Props = {
feed: PostProps[];
};
const Blog: React.FC<Props> = (props) => {
return (
<Layout>
<div className="page">
<h1>Public Feed</h1>
<main>
{props.feed.map((post) => (
<div key={post.id} className="post">
<Post post={post} />
</div>
))}
</main>
</div>
<style jsx>{`
.post {
background: white;
transition: box-shadow 0.1s ease-in;
}
.post:hover {
box-shadow: 1px 1px 3px #aaa;
}
.post + .post {
margin-top: 2rem;
}
`}</style>
</Layout>
);
};
export default Blog;

@ -0,0 +1,91 @@
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: React.FC<PostProps> = (props) => {
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;

@ -0,0 +1,73 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
model Account {
id Int @id @default(autoincrement())
userId Int @map("user_id")
type String
provider String
providerAccountId String @map("provider_account_id")
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
oauth_token_secret String?
oauth_token String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
@@map("accounts")
}
model Session {
id Int @id @default(autoincrement())
sessionToken String @unique @map("session_token")
userId Int @map("user_id")
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("sessions")
}
model User {
id Int @id @default(autoincrement())
name String?
email String? @unique
emailVerified DateTime? @map("email_verified")
image String?
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
posts Post[]
accounts Account[]
sessions Session[]
@@map(name: "users")
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
@@map("verificationtokens")
}

@ -0,0 +1,70 @@
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()
const userData: Prisma.UserCreateInput[] = [
{
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: [
{
title: 'Join the Prisma Slack',
content: 'https://slack.prisma.io',
published: true,
},
],
},
},
{
name: 'Nilu',
email: 'nilu@prisma.io',
posts: {
create: [
{
title: 'Follow Prisma on Twitter',
content: 'https://www.twitter.com/prisma',
published: true,
},
],
},
},
{
name: 'Mahmoud',
email: 'mahmoud@prisma.io',
posts: {
create: [
{
title: 'Ask a question about Prisma on GitHub',
content: 'https://www.github.com/prisma/prisma/discussions',
published: true,
},
{
title: 'Prisma on YouTube',
content: 'https://pris.ly/youtube',
},
],
},
},
]
async function main() {
console.log(`Start seeding ...`)
for (const u of userData) {
const user = await prisma.user.create({
data: u,
})
console.log(`Created user with id: ${user.id}`)
}
console.log(`Seeding finished.`)
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

@ -0,0 +1,35 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
}
}
Loading…
Cancel
Save