Unverified Commit fe312ed4 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

Update MySQL example. (#34784)

Changes from https://github.com/planetscale/nextjs-starter.

Realized the current example was not only out of date, but the demo was broken. Will update the demo site post-merge here 👍 
parent 079b5073
DATABASE_URL=mysql://<USERNAME>:<PLAIN_TEXT_PASSWORD>@<ACCESS_HOST_URL>/<DATABASE_NAME>?sslaccept=strict
# Example .env.local file for MySQL Database credentials
MYSQL_HOST=
MYSQL_DATABASE=
MYSQL_USERNAME=
MYSQL_PASSWORD=
MYSQL_PORT=
# MySQL Example # Next.js + MySQL
This is an example of using [MySQL](https://www.mysql.com/) in a Next.js project. This is a [Next.js](https://nextjs.org/) project that uses [Prisma](https://www.prisma.io/) to connect to a [PlanetScale](https://planetscale.com/) MySQL database and [Tailwind CSS](https://tailwindcss.com/) for styling.
## Demo ## Demo
### [https://next-mysql.vercel.app](https://next-mysql.vercel.app/) https://next-mysql.vercel.app
## Deploy your own ## Prerequisites
- [Node.js](https://nodejs.org/en/download/)
- [PlanetScale CLI](https://github.com/planetscale/cli)
- Authenticate the CLI with the following command:
```sh
pscale auth login
```
## Set up the database
Create a new database with the following command:
Once you have access to [the environment variables you'll need](#step-5-set-up-environment-variables), deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example): ```sh
pscale database create <DATABASE_NAME>
```
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mysql&project-name=nextjs-mysql&repository-name=nextjs-mysql&env=MYSQL_HOST,MYSQL_DATABASE,MYSQL_USERNAME,MYSQL_PASSWORD&envDescription=Required%20to%20connect%20the%20app%20with%20MySQL&envLink=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-mysql%23step-2-set-up-environment-variables&demo-title=Next.js%20%2B%20MySQL%20Demo&demo-description=A%20simple%20app%20demonstrating%20Next.js%20and%20MySQL%20&demo-url=https%3A%2F%2Fnext-mysql.vercel.app%2F) > A branch, `main`, was automatically created when you created your database, so you can use that for `BRANCH_NAME` in the steps below.
## How to use ## Set up the starter Next.js app
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example: Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash ```bash
npx create-next-app --example with-mysql next-mysql-app npx create-next-app --example with-mysql nextjs-mysql
# or # or
yarn create next-app --example with-mysql next-mysql-app yarn create next-app --example with-mysql nextjs-mysql
``` ```
## Configuration Next, you'll need to create a database username and password through the CLI to connect to your application. If you'd prefer to use the dashboard for this step, you can find those instructions in the [Connection Strings documentation](https://docs.planetscale.com/concepts/connection-strings#creating-a-password) and then come back here to finish setup.
### Step 1. Set up a MySQL database
Set up a MySQL server either locally or any cloud provider. First, create your `.env` file by renaming the `.env.example` file to `.env`:
### Step 2. Set up environment variables ```sh
mv .env.example .env
```
Copy the `env.local.example` file in this directory to `.env.local` (which will be ignored by Git): Next, using the PlanetScale CLI, create a new username and password for the branch of your database:
```bash ```sh
cp .env.local.example .env.local pscale password create <DATABASE_NAME> <BRANCH_NAME> <PASSWORD_NAME>
``` ```
Set each variable on `.env.local`: > The `PASSWORD_NAME` value represents the name of the username and password being generated. You can have multiple credentials for a branch, so this gives you a way to categorize them. To manage your passwords in the dashboard, go to your database overview page, click "Settings", and then click "Passwords".
- `MYSQL_HOST` - Your MySQL host URL.
- `MYSQL_DATABASE` - The name of the MySQL database you want to use.
- `MYSQL_USERNAME` - The name of the MySQL user with access to database.
- `MYSQL_PASSWORD` - The passowrd of the MySQL user.
### Step 3. Run migration script Take note of the values returned to you, as you won't be able to see this password again.
You'll need to run a migration to create the necessary table for the example. ```text
Password production-password was successfully created.
Please save the values below as they will not be shown again
```bash NAME USERNAME ACCESS HOST URL ROLE PLAIN TEXT
npm run migrate --------------------- -------------- ----------------------------------- ------------------ -------------------------------------------------------
# or production-password xxxxxxxxxxxxx xxxxxx.us-east-2.psdb.cloud Can Read & Write pscale_pw_xxxxxxx
yarn migrate
``` ```
### Step 4. Run Next.js in development mode You'll use these properties to construct your connection string, which will be the value for `DATABASE_URL` in your `.env` file. Update the `DATABASE_URL` property with your connection string in the following format:
```bash ```text
npm install mysql://<USERNAME>:<PLAIN_TEXT_PASSWORD>@<ACCESS_HOST_URL>/<DATABASE_NAME>?sslaccept=strict
npm run dev
# or
yarn install
yarn dev
``` ```
Your app should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions). Push the database schema to your PlanetScale database using Prisma.
`npx prisma db push`
Run the seed script to populate your database with `Product` and `Category` data.
`npx run seed`
## Deploy on Vercel ## Run the App
You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). Run the app with following command:
#### Deploy Your Local Project `npm run dev`
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example). Open your browser at [localhost:3000](localhost:3000) to see the running application.
## Deploy your own
After you've got your application running locally, it's time to deploy it. To do so, you'll need to promote your database branch (`main` by default) to be the production branch ([read the branching documentation for more information](https://docs.planetscale.com/concepts/branching)).
```sh
pscale branch promote <DATABASE_NAME> <BRANCH_NAME>
```
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file. Now that your branch has been promoted to production, you can either use the existing password you generated earlier for running locally or create a new password. Regardless, you'll need a password in the deployment steps below.
#### Deploy from Our Template Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
Alternatively, you can deploy using our template by clicking on the Deploy button below. [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mysql&project-name=with-mysql&repository-name=with-mysql&env=DATABASE_URL)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mysql&project-name=nextjs-mysql&repository-name=nextjs-mysql&env=MYSQL_HOST,MYSQL_DATABASE,MYSQL_USERNAME,MYSQL_PASSWORD&envDescription=Required%20to%20connect%20the%20app%20with%20MySQL&envLink=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-mysql%23step-2-set-up-environment-variables&demo-title=Next.js%20%2B%20MySQL%20Demo&demo-description=A%20simple%20app%20demonstrating%20Next.js%20and%20MySQL%20&demo-url=https%3A%2F%2Fnext-mysql.vercel.app%2F) > Make sure to update the `DATABASE_URL` variable during this setup process.
import Image from 'next/image'
export default function Product({ product }) {
const { name, description, price, image, category } = product
return (
<div
className="max-w-xs rounded overflow-hidden shadow-lg"
key={product.id}
>
<Image
className="w-full"
width={320}
height={160}
src={image}
alt={name}
/>
<div className="px-6 py-4">
<div className="font-bold text-xl mb-2">{name}</div>
<p className="text-gray-700 text-base">{description}</p>
<p className="text-gray-900 text-xl">${price}</p>
</div>
<div className="px-6 pt-4 pb-2">
<span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
{category.name}
</span>
</div>
</div>
)
}
import Link from 'next/link'
import cn from 'clsx'
function ButtonLink({ href = '/', className = '', children }) {
return (
<Link href={href}>
<a
className={cn(
'bg-black',
'text-white',
'p-2',
'rounded',
'uppercase',
'text-sm',
'font-bold',
{
[className]: Boolean(className),
}
)}
>
{children}
</a>
</Link>
)
}
export default ButtonLink
import cn from 'clsx'
function Button({
onClick = console.log,
className = '',
children = null,
type = null,
disabled = false,
}) {
return (
<button
type={type}
onClick={onClick}
disabled={disabled}
className={cn(
'bg-black',
'text-white',
'p-2',
'rounded',
'uppercase',
'text-sm',
'font-bold',
{
[className]: Boolean(className),
}
)}
>
{children}
</button>
)
}
export default Button
function Container({ className = '', children }) {
return <div className={'container mx-auto px-8 ' + className}>{children}</div>
}
export default Container
import { useState, useEffect } from 'react'
import Router, { useRouter } from 'next/router'
import Button from '../button'
export default function EntryForm() {
const [_title, setTitle] = useState('')
const [_content, setContent] = useState('')
const [submitting, setSubmitting] = useState(false)
const router = useRouter()
const { id, title, content } = router.query
useEffect(() => {
if (typeof title === 'string') {
setTitle(title)
}
if (typeof content === 'string') {
setContent(content)
}
}, [title, content])
async function submitHandler(e) {
e.preventDefault()
setSubmitting(true)
try {
const res = await fetch('/api/edit-entry', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id,
title: _title,
content: _content,
}),
})
const json = await res.json()
setSubmitting(false)
if (!res.ok) throw Error(json.message)
Router.push('/')
} catch (e) {
throw Error(e.message)
}
}
return (
<form onSubmit={submitHandler}>
<div className="my-4">
<label htmlFor="title">
<h3 className="font-bold">Title</h3>
</label>
<input
id="title"
className="shadow border rounded w-full"
type="text"
name="title"
value={_title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="my-4">
<label htmlFor="content">
<h3 className="font-bold">Content</h3>
</label>
<textarea
className="shadow border resize-none focus:shadow-outline w-full h-48"
id="content"
name="content"
value={_content}
onChange={(e) => setContent(e.target.value)}
/>
</div>
<Button disabled={submitting} type="submit">
{submitting ? 'Saving ...' : 'Save'}
</Button>
</form>
)
}
import { useState } from 'react'
import Link from 'next/link'
import { mutate } from 'swr'
import ButtonLink from '@/components/button-link'
import Button from '@/components/button'
function Entry({ id, title, content }) {
const [deleting, setDeleting] = useState(false)
async function deleteEntry() {
setDeleting(true)
let res = await fetch(`/api/delete-entry?id=${id}`, { method: 'DELETE' })
let json = await res.json()
if (!res.ok) throw Error(json.message)
mutate('/api/get-entries')
setDeleting(false)
}
return (
<div>
<div className="flex items-center">
<Link href={`/entry/${id}`}>
<a className="font-bold py-2">{title}</a>
</Link>
<div className="flex ml-4">
<ButtonLink
href={`/entry/edit/${id}?title=${title}&content=${content}`}
className="h-5 py-0 mx-1"
>
Edit
</ButtonLink>
<Button
disabled={deleting}
onClick={deleteEntry}
className="h-5 py-0 mx-1"
>
{deleting ? 'Deleting ...' : 'Delete'}
</Button>
</div>
</div>
<p>{content}</p>
</div>
)
}
export default Entry
import Entry from './entry'
function Entries({ entries }) {
if (entries) {
return (
<div>
{entries.map((e) => (
<div key={e.id} className="py-2">
<Entry id={e.id} title={e.title} content={e.content} />
</div>
))}
</div>
)
} else {
return null
}
}
export default Entries
import { useState } from 'react'
import Router from 'next/router'
import Button from '@/components/button'
export default function EntryForm() {
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [submitting, setSubmitting] = useState(false)
async function submitHandler(e) {
setSubmitting(true)
e.preventDefault()
try {
const res = await fetch('/api/create-entry', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title,
content,
}),
})
setSubmitting(false)
const json = await res.json()
if (!res.ok) throw Error(json.message)
Router.push('/')
} catch (e) {
throw Error(e.message)
}
}
return (
<form onSubmit={submitHandler}>
<div className="my-4">
<label htmlFor="title">
<h3 className="font-bold">Title</h3>
</label>
<input
id="title"
className="shadow border rounded w-full"
type="text"
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="my-4">
<label htmlFor="content">
<h3 className="font-bold">Content</h3>
</label>
<textarea
className="shadow border resize-none focus:shadow-outline w-full h-48"
id="content"
name="content"
value={content}
onChange={(e) => setContent(e.target.value)}
/>
</div>
<Button disabled={submitting} type="submit">
{submitting ? 'Creating ...' : 'Create'}
</Button>
</form>
)
}
import PoweredByVercel from '../powered-by-vercel'
function Footer() {
return (
<footer className="container mx-auto fixed bottom-0 right-0 left-0 flex justify-center items-center h-24">
<a href="https://vercel.com?utm_source=next-mysql">
<PoweredByVercel />
</a>
</footer>
)
}
export default Footer
import Link from 'next/link'
import Container from '@/components/container'
import ButtonLink from '@/components/button-link'
export default function Nav({ title = 'Entries' }) {
return (
<Container className="py-4">
<nav>
<div className="flex justify-between items-center">
<Link href="/">
<a className="font-bold text-3xl">{title}</a>
</Link>
<ButtonLink href="/new">New Entry</ButtonLink>
</div>
</nav>
</Container>
)
}
function PoweredByVercel() {
return (
<svg width="212" height="44" viewBox="0 0 212 44" fill="none">
<rect width="212" height="44" rx="8" fill="black" />
<path
d="M60.4375 15.2266V26.5H61.8438V22.4766H64.6797C66.7969 22.4766 68.3047 20.9844 68.3047 18.875C68.3047 16.7266 66.8281 15.2266 64.6953 15.2266H60.4375ZM61.8438 16.4766H64.3281C65.9609 16.4766 66.8594 17.3281 66.8594 18.875C66.8594 20.3672 65.9297 21.2266 64.3281 21.2266H61.8438V16.4766ZM73.3441 26.6484C75.7425 26.6484 77.2269 24.9922 77.2269 22.2891C77.2269 19.5781 75.7425 17.9297 73.3441 17.9297C70.9456 17.9297 69.4613 19.5781 69.4613 22.2891C69.4613 24.9922 70.9456 26.6484 73.3441 26.6484ZM73.3441 25.4375C71.7503 25.4375 70.8519 24.2812 70.8519 22.2891C70.8519 20.2891 71.7503 19.1406 73.3441 19.1406C74.9378 19.1406 75.8363 20.2891 75.8363 22.2891C75.8363 24.2812 74.9378 25.4375 73.3441 25.4375ZM89.2975 18.0781H87.9459L86.2897 24.8125H86.1647L84.2819 18.0781H82.9928L81.11 24.8125H80.985L79.3288 18.0781H77.9694L80.3288 26.5H81.6881L83.5631 19.9844H83.6881L85.5709 26.5H86.9381L89.2975 18.0781ZM93.8213 19.1172C95.1572 19.1172 96.0478 20.1016 96.0791 21.5938H91.4384C91.54 20.1016 92.4775 19.1172 93.8213 19.1172ZM96.04 24.3203C95.6884 25.0625 94.9541 25.4609 93.8681 25.4609C92.4384 25.4609 91.5088 24.4062 91.4384 22.7422V22.6797H97.4931V22.1641C97.4931 19.5469 96.1103 17.9297 93.8369 17.9297C91.5244 17.9297 90.04 19.6484 90.04 22.2969C90.04 24.9609 91.5009 26.6484 93.8369 26.6484C95.6806 26.6484 96.9931 25.7578 97.3838 24.3203H96.04ZM99.2825 26.5H100.626V21.2812C100.626 20.0938 101.556 19.2344 102.837 19.2344C103.103 19.2344 103.587 19.2812 103.697 19.3125V17.9688C103.525 17.9453 103.243 17.9297 103.025 17.9297C101.908 17.9297 100.939 18.5078 100.689 19.3281H100.564V18.0781H99.2825V26.5ZM108.181 19.1172C109.517 19.1172 110.408 20.1016 110.439 21.5938H105.798C105.9 20.1016 106.838 19.1172 108.181 19.1172ZM110.4 24.3203C110.048 25.0625 109.314 25.4609 108.228 25.4609C106.798 25.4609 105.869 24.4062 105.798 22.7422V22.6797H111.853V22.1641C111.853 19.5469 110.47 17.9297 108.197 17.9297C105.884 17.9297 104.4 19.6484 104.4 22.2969C104.4 24.9609 105.861 26.6484 108.197 26.6484C110.041 26.6484 111.353 25.7578 111.744 24.3203H110.4ZM116.76 26.6484C117.924 26.6484 118.924 26.0938 119.455 25.1562H119.58V26.5H120.861V14.7344H119.518V19.4062H119.4C118.924 18.4844 117.932 17.9297 116.76 17.9297C114.619 17.9297 113.221 19.6484 113.221 22.2891C113.221 24.9375 114.603 26.6484 116.76 26.6484ZM117.072 19.1406C118.596 19.1406 119.549 20.3594 119.549 22.2891C119.549 24.2344 118.603 25.4375 117.072 25.4375C115.533 25.4375 114.611 24.2578 114.611 22.2891C114.611 20.3281 115.541 19.1406 117.072 19.1406ZM131.534 26.6484C133.667 26.6484 135.065 24.9219 135.065 22.2891C135.065 19.6406 133.674 17.9297 131.534 17.9297C130.378 17.9297 129.354 18.5 128.893 19.4062H128.768V14.7344H127.424V26.5H128.706V25.1562H128.831C129.362 26.0938 130.362 26.6484 131.534 26.6484ZM131.221 19.1406C132.76 19.1406 133.674 20.3203 133.674 22.2891C133.674 24.2578 132.76 25.4375 131.221 25.4375C129.69 25.4375 128.737 24.2344 128.737 22.2891C128.737 20.3438 129.69 19.1406 131.221 19.1406ZM137.261 29.5469C138.753 29.5469 139.425 28.9688 140.143 27.0156L143.433 18.0781H142.003L139.698 25.0078H139.573L137.261 18.0781H135.808L138.925 26.5078L138.768 27.0078C138.417 28.0234 137.995 28.3906 137.222 28.3906C137.034 28.3906 136.823 28.3828 136.659 28.3516V29.5C136.847 29.5312 137.081 29.5469 137.261 29.5469ZM154.652 26.5L158.55 15.2266H156.402L153.589 24.1484H153.457L150.621 15.2266H148.394L152.332 26.5H154.652ZM162.668 19.3203C163.832 19.3203 164.598 20.1328 164.637 21.3984H160.613C160.699 20.1484 161.512 19.3203 162.668 19.3203ZM164.652 24.1484C164.371 24.7812 163.707 25.1328 162.746 25.1328C161.473 25.1328 160.652 24.2422 160.605 22.8203V22.7188H166.574V22.0938C166.574 19.3984 165.113 17.7812 162.676 17.7812C160.199 17.7812 158.66 19.5078 158.66 22.2578C158.66 25.0078 160.176 26.6719 162.691 26.6719C164.707 26.6719 166.137 25.7031 166.488 24.1484H164.652ZM168.199 26.5H170.137V21.5625C170.137 20.3672 171.012 19.5859 172.27 19.5859C172.598 19.5859 173.113 19.6406 173.262 19.6953V17.8984C173.082 17.8438 172.738 17.8125 172.457 17.8125C171.356 17.8125 170.434 18.4375 170.199 19.2812H170.067V17.9531H168.199V26.5ZM181.7 20.8281C181.497 19.0312 180.168 17.7812 177.973 17.7812C175.403 17.7812 173.895 19.4297 173.895 22.2031C173.895 25.0156 175.411 26.6719 177.981 26.6719C180.145 26.6719 181.489 25.4688 181.7 23.6797H179.856C179.653 24.5703 178.981 25.0469 177.973 25.0469C176.653 25.0469 175.856 24 175.856 22.2031C175.856 20.4297 176.645 19.4062 177.973 19.4062C179.036 19.4062 179.676 20 179.856 20.8281H181.7ZM186.817 19.3203C187.981 19.3203 188.747 20.1328 188.786 21.3984H184.762C184.848 20.1484 185.661 19.3203 186.817 19.3203ZM188.802 24.1484C188.52 24.7812 187.856 25.1328 186.895 25.1328C185.622 25.1328 184.802 24.2422 184.755 22.8203V22.7188H190.723V22.0938C190.723 19.3984 189.262 17.7812 186.825 17.7812C184.348 17.7812 182.809 19.5078 182.809 22.2578C182.809 25.0078 184.325 26.6719 186.841 26.6719C188.856 26.6719 190.286 25.7031 190.637 24.1484H188.802ZM192.427 26.5H194.364V14.6484H192.427V26.5Z"
fill="white"
/>
<path d="M23.3248 13L32.6497 29H14L23.3248 13Z" fill="white" />
<line x1="43.5" y1="2.18557e-08" x2="43.5" y2="44" stroke="#5E5E5E" />
</svg>
)
}
export default PoweredByVercel
import mysql from 'serverless-mysql'
export const db = mysql({
config: {
host: process.env.MYSQL_HOST,
database: process.env.MYSQL_DATABASE,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
port: parseInt(process.env.MYSQL_PORT),
},
})
export async function query(
q: string,
values: (string | number)[] | string | number = []
) {
try {
const results = await db.query(q, values)
await db.end()
return results
} catch (e) {
throw Error(e.message)
}
}
import { PrismaClient } from '@prisma/client'
let prisma
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma
import useSWR from 'swr'
function fetcher(url: string) {
return window.fetch(url).then((res) => res.json())
}
export function useEntries() {
const { data, error } = useSWR(`/api/get-entries`, fetcher)
return {
entries: data,
isLoading: !error && !data,
isError: error,
}
}
export function useEntry(id: string) {
return useSWR(`/api/get-entry?id=${id}`, fetcher)
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
module.exports = {
reactStrictMode: true,
}
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"migrate": "node scripts/migrate-db.js" "seed": "node prisma/seed.js"
}, },
"dependencies": { "dependencies": {
"bad-words": "^3.0.4", "@prisma/client": "3.10.0",
"clsx": "^1.1.1",
"dotenv": "^10.0.0",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "17.0.2",
"react-dom": "^17.0.2", "react-dom": "17.0.2"
"react-loading-skeleton": "^2.1.1",
"serverless-mysql": "^1.5.4",
"swr": "^0.3.9"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^14.14.6", "autoprefixer": "10.4.2",
"@types/react": "^16.9.55", "postcss": "8.4.7",
"postcss-flexbugs-fixes": "4.2.1", "prisma": "3.10.0",
"postcss-preset-env": "^6.7.0", "tailwindcss": "3.0.23"
"tailwindcss": "^1.7.4",
"typescript": "^4.0.5"
} }
} }
import '../styles/globals.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
import '../styles/index.css'
import Footer from '@/components/footer'
function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<Footer />
</>
)
}
export default MyApp
import { NextApiHandler } from 'next'
import Filter from 'bad-words'
import { query } from '../../lib/db'
const filter = new Filter()
const handler: NextApiHandler = async (req, res) => {
const { title, content } = req.body
try {
if (!title || !content) {
return res
.status(400)
.json({ message: '`title` and `content` are both required' })
}
const results = await query(
`
INSERT INTO entries (title, content)
VALUES (?, ?)
`,
[filter.clean(title), filter.clean(content)]
)
return res.json(results)
} catch (e) {
res.status(500).json({ message: e.message })
}
}
export default handler
import { NextApiHandler } from 'next'
import { query } from '../../lib/db'
const handler: NextApiHandler = async (req, res) => {
const { id } = req.query
try {
if (!id) {
return res.status(400).json({ message: '`id` required' })
}
if (typeof parseInt(id.toString()) !== 'number') {
return res.status(400).json({ message: '`id` must be a number' })
}
const results = await query(
`
DELETE FROM entries
WHERE id = ?
`,
id
)
res.json(results)
} catch (e) {
res.status(500).json({ message: e.message })
}
}
export default handler
import { NextApiHandler } from 'next'
import Filter from 'bad-words'
import { query } from '../../lib/db'
const filter = new Filter()
const handler: NextApiHandler = async (req, res) => {
const { id, title, content } = req.body
try {
if (!id || !title || !content) {
return res
.status(400)
.json({ message: '`id`,`title`, and `content` are all required' })
}
const results = await query(
`
UPDATE entries
SET title = ?, content = ?
WHERE id = ?
`,
[filter.clean(title), filter.clean(content), id]
)
return res.json(results)
} catch (e) {
res.status(500).json({ message: e.message })
}
}
export default handler
import { NextApiHandler } from 'next'
import { query } from '../../lib/db'
const handler: NextApiHandler = async (_, res) => {
try {
const results = await query(`
SELECT * FROM entries
ORDER BY id DESC
LIMIT 10
`)
return res.json(results)
} catch (e) {
res.status(500).json({ message: e.message })
}
}
export default handler
import { NextApiHandler } from 'next'
import { query } from '../../lib/db'
const handler: NextApiHandler = async (req, res) => {
const { id } = req.query
try {
if (!id) {
return res.status(400).json({ message: '`id` required' })
}
if (typeof parseInt(id.toString()) !== 'number') {
return res.status(400).json({ message: '`id` must be a number' })
}
const results = await query(
`
SELECT id, title, content
FROM entries
WHERE id = ?
`,
id
)
return res.json(results[0])
} catch (e) {
res.status(500).json({ message: e.message })
}
}
export default handler
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import prisma from './../../lib/prisma.js'
export default async function handler(req, res) {
if (req.method === 'GET') {
try {
const data = await prisma.product.findMany({})
return res.status(200).json({ data })
} catch (err) {
console.error(err)
return res.status(500).json({ msg: 'Something went wrong' })
}
} else {
return res.status(405).json({ msg: 'Method not allowed' })
}
}
import { useRouter } from 'next/router'
import { useEntry } from '@/lib/swr-hooks'
import Container from '@/components/container'
import Nav from '@/components/nav'
export default function EditEntryPage() {
const router = useRouter()
const id = router.query.id?.toString()
const { data } = useEntry(id)
if (data) {
return (
<>
<Nav title="View" />
<Container>
<h1 className="font-bold text-3xl my-2">{data.title}</h1>
<p>{data.content}</p>
</Container>
</>
)
} else {
return (
<>
<Nav title="View" />
<Container>
<h1 className="font-bold text-3xl my-2">...</h1>
<p>...</p>
</Container>
</>
)
}
}
import Container from '@/components/container'
import Nav from '@/components/nav'
import EditEntryForm from '@/components/edit-entry-form'
export default function EditEntryPage() {
return (
<>
<Nav title="Edit" />
<Container>
<EditEntryForm />
</Container>
</>
)
}
import Head from 'next/head'
import Product from '../components/Product'
import prisma from '../lib/prisma'
export default function Home({ products }) {
return (
<div>
<Head>
<title>PlanetScale Next.js Quickstart</title>
<meta name="description" content="PlanetScale Quickstart for Next.js" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="p-10 mx-auto max-w-4xl">
<h1 className="text-6xl font-bold mb-4 text-center">Next.js Starter</h1>
<p className="mb-20 text-xl text-center">
🔥 Shop from the hottest items in the world 🔥
</p>
<div className="grid md:grid-cols-3 sm:grid-cols-2 grid-cols-1 justify-items-center gap-4">
{products.map((product) => (
<Product product={product} key={product.id} />
))}
</div>
</main>
<footer></footer>
</div>
)
}
export async function getStaticProps(context) {
const data = await prisma.product.findMany({
include: {
category: true,
},
})
//convert decimal value to string to pass through as json
const products = data.map((product) => ({
...product,
price: product.price.toString(),
}))
return {
props: { products },
}
}
import Skeleton from 'react-loading-skeleton'
import Nav from '@/components/nav'
import Container from '@/components/container'
import Entries from '@/components/entries'
import { useEntries } from '@/lib/swr-hooks'
export default function IndexPage() {
const { entries, isLoading } = useEntries()
if (isLoading) {
return (
<div>
<Nav />
<Container>
<Skeleton width={180} height={24} />
<Skeleton height={48} />
<div className="my-4" />
<Skeleton width={180} height={24} />
<Skeleton height={48} />
<div className="my-4" />
<Skeleton width={180} height={24} />
<Skeleton height={48} />
</Container>
</div>
)
}
return (
<div>
<Nav />
<Container>
<Entries entries={entries} />
</Container>
</div>
)
}
import Nav from '@/components/nav'
import Container from '@/components/container'
import EntryForm from '@/components/entry-form'
export default function NewEntryPage() {
return (
<>
<Nav title="New" />
<Container className="w-full lg:w-2/4">
<EntryForm />
</Container>
</>
)
}
module.exports = { module.exports = {
plugins: [ plugins: {
'tailwindcss', tailwindcss: {},
'postcss-flexbugs-fixes', autoprefixer: {},
[ },
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
features: {
'custom-properties': false,
},
},
],
],
} }
const { Prisma } = require('@prisma/client')
const categories = [
{
name: 'Hats',
description: 'Things you can wear on your head',
},
{
name: 'Socks',
description: 'Things you can wear on your feet',
},
{
name: 'Shirts',
description: 'Things you wear on the top half of your body',
},
]
const products = [
{
name: 'Cool hat.',
description: 'A nice hat to wear on your head',
price: new Prisma.Decimal(19.95),
image: '/images/placeholder.jpg',
category_id: 1,
},
{
name: 'Grey T-Shirt',
description: 'A nice shirt that you can wear on your body',
price: new Prisma.Decimal(22.95),
image: '/images/placeholder.jpg',
category_id: 3,
},
{
name: 'Socks',
description: 'Cool socks that you can wear on your feet',
price: new Prisma.Decimal(12.95),
image: '/images/placeholder.jpg',
category_id: 2,
},
{
name: 'Sweatshirt',
description: 'Cool sweatshirt that you can wear on your body',
price: new Prisma.Decimal(12.95),
image: '/images/placeholder.jpg',
category_id: 3,
},
]
module.exports = {
products,
categories,
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
referentialIntegrity = "prisma"
}
model Product {
id Int @id @default(autoincrement())
name String
description String
price Decimal
image String
category Category? @relation(fields: [category_id], references: [id])
category_id Int
@@index([category_id])
}
model Category {
id Int @id @default(autoincrement())
name String
description String
products Product[]
}
const { PrismaClient } = require('@prisma/client')
const { categories, products } = require('./data.js')
const prisma = new PrismaClient()
const load = async () => {
try {
await prisma.category.deleteMany()
console.log('Deleted records in category table')
await prisma.product.deleteMany()
console.log('Deleted records in product table')
await prisma.$queryRaw`ALTER TABLE Product AUTO_INCREMENT = 1`
console.log('reset product auto increment to 1')
await prisma.$queryRaw`ALTER TABLE Category AUTO_INCREMENT = 1`
console.log('reset category auto increment to 1')
await prisma.category.createMany({
data: categories,
})
console.log('Added category data')
await prisma.product.createMany({
data: products,
})
console.log('Added product data')
} catch (e) {
console.error(e)
process.exit(1)
} finally {
await prisma.$disconnect()
}
}
load()
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
\ No newline at end of file
const path = require('path')
const envPath = path.resolve(process.cwd(), '.env.local')
console.log({ envPath })
require('dotenv').config({ path: envPath })
const mysql = require('serverless-mysql')
const db = mysql({
config: {
host: process.env.MYSQL_HOST,
database: process.env.MYSQL_DATABASE,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
port: process.env.MYSQL_PORT,
},
})
async function query(q) {
try {
const results = await db.query(q)
await db.end()
return results
} catch (e) {
throw Error(e.message)
}
}
// Create "entries" table if doesn't exist
async function migrate() {
try {
await query(`
CREATE TABLE IF NOT EXISTS entries (
id INT AUTO_INCREMENT PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at
TIMESTAMP
NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
)
`)
console.log('migration ran successfully')
} catch (e) {
console.error('could not run migration, double check your credentials.')
process.exit(1)
}
}
migrate().then(() => process.exit())
@tailwind base;
@tailwind components;
@tailwind utilities;
@tailwind base;
/* Write your own custom base styles here */
/* Start purging... */
@tailwind components;
/* Stop purging. */
/* Write your own custom component styles here */
.btn-blue {
@apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}
/* Start purging... */
@tailwind utilities;
/* Stop purging. */
/* Your own custom utilities */
module.exports = { module.exports = {
future: { content: [
removeDeprecatedGapUtilities: true, './pages/**/*.{js,ts,jsx,tsx}',
purgeLayersByDefault: true, './components/**/*.{js,ts,jsx,tsx}',
}, ],
purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
theme: { theme: {
extend: { extend: {},
colors: {
'accent-1': '#333',
},
},
}, },
variants: {},
plugins: [], plugins: [],
} }
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"],
"@/lib/*": ["lib/*"]
},
"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"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment