feat(examples): add with-turso (#61291)

This commit is contained in:
Jamie Barton 2024-05-01 17:41:47 +01:00 committed by GitHub
parent c9a34f8b5c
commit a0df9860c4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 393 additions and 0 deletions

View file

@ -0,0 +1,2 @@
TURSO_DB_URL=
TURSO_DB_TOKEN=

38
examples/with-turso/.gitignore vendored Normal file
View file

@ -0,0 +1,38 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
*.db

View file

@ -0,0 +1,105 @@
# Turso
[Turso](https://turso.tech) is a SQLite-compatible database built on libSQL, the Open Contribution fork of SQLite. It enables scaling to hundreds of thousands of databases per organization and supports replication to any location, including your own servers, for microsecond-latency access.
* [Turso Documentation](https://docs.turso.tech)
* [Turso Support](https://discord.com/invite/4B5D7hYwub)
## Features
* Uses SQLite `dev.db` locally
* App Router
* Server Actions
## How to use
You can run this example locally using SQLite. The example will automatically create a `todos` table using the file `dev.db`.
Create a new Next app using the `with-turso` example:
```bash
npx create-next-app --example with-turso with-turso-app
```
```bash
yarn create next-app --example with-turso with-turso-app
```
```bash
pnpm create next-app --example with-turso with-turso-app
```
Then install the dependencies and run the Next.js development server:
```bash
npm install
npm run dev
# or
yarn install
yarn dev
# or
#
pnpm install
pnpm dev
```
You should now be able to go to [http://localhost:3000](http://localhost:3000).
## Deploy to Vercel
You can deploy this app to Vercel in a few simple steps:
1. **Signup to Turso**
Install the Turso CLI and login using GitHub:
```bash
# macOS
brew install tursodatabase/tap/turso
# Windows (WSL) & Linux:
# curl -sSfL https://get.tur.so/install.sh | bash
```
2. **Create a database**
Begin by creating your first database:
```bash
turso db create [database-name]
```
3. **Create a table**
Connect to the turso shell and create your first table:
```bash
turso db shell <database-name>
```
```bash
CREATE TABLE todos(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT NOT NULL)
```
4. **Retrieve database URL**
You'll need to fetch your database URL and assign it to `TURSO_DB_URL` on deployment:
```bash
turso db show <database-name> --url
```
5. **Create database auth token**
Now create an access token and assign it to `TURSO_DB_TOKEN` on deployment:
```bash
turso db tokens create <database-name>
```
6. **Deploy to Vercel**
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-turso&env=TURSO_DB_URL,TURSO_DB_TOKEN)

View file

@ -0,0 +1,23 @@
"use server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/turso";
export const addTodo = async (formData: FormData) => {
await db.execute({
sql: "INSERT INTO todos (description) VALUES (?)",
args: [formData.get("description") as string],
});
revalidatePath("/");
};
export const removeTodo = async (formData: FormData) => {
await db.execute({
sql: "DELETE FROM todos WHERE id = ?",
args: [formData.get("id") as string],
});
revalidatePath("/");
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1,46 @@
"use client";
import { useRef } from "react";
import { useFormStatus } from "react-dom";
import { addTodo } from "./actions";
function Submit() {
const { pending } = useFormStatus();
return (
<button type="submit" aria-disabled={pending} className="sr-only">
Add
</button>
);
}
export function Form() {
const formRef = useRef<HTMLFormElement>(null);
formRef.current?.reset();
return (
<form
action={async (formData) => {
await addTodo(formData);
formRef.current?.reset();
}}
className="rounded-md border border-gray-300 p-3 shadow-sm"
ref={formRef}
>
<input
id="description"
name="description"
placeholder="Insert new todo"
className="w-full text-black outline-none"
required
aria-label="Description of todo"
type="text"
autoFocus
/>
<Submit />
</form>
);
}

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Next.js + Turso",
description: "Next.js Server Actions Demo + Turso",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}

View file

@ -0,0 +1,19 @@
import { TodoList } from './todo-list'
import { Form } from "./form";
export default function Home() {
return (
<main className="max-w-2xl mx-auto space-y-12 px-6 py-32">
<div className="space-y-3 text-center">
<h1 className="text-3xl font-medium">Turso</h1>
<p className="text-gray-500">Local SQLite with libSQL and Turso</p>
</div>
<div className="space-y-3">
<TodoList />
<Form />
</div>
</main >
);
}

View file

@ -0,0 +1,31 @@
import { type TodoItem, Todo } from "./todo";
import { db } from "@/lib/turso";
// The code below can be removed in production apps
// Useful for getting started locally with SQLite
async function findOrCreateTodosTable() {
const result = await db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='todos'")
if (!result || result?.rows?.length === 0) {
await db.execute("CREATE TABLE todos(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT NOT NULL)")
}
}
export async function TodoList() {
await findOrCreateTodosTable()
const result = await db.execute("SELECT * FROM todos");
const rows = result.rows as unknown as TodoItem[];
if (!result || result?.rows?.length === 0) return null;
return rows.map((row, index) => (
<Todo
key={index}
item={{
id: row.id,
description: row.description,
}}
/>
));
}

View file

@ -0,0 +1,23 @@
"use client";
import { removeTodo } from "./actions";
export type TodoItem = {
id: number;
description: string;
};
export function Todo({ item }: { item: TodoItem }) {
return (
<li className="flex items-center justify-between rounded-md border border-gray-100 p-3">
<div className="flex w-full items-center space-x-3">
{item.description}
</div>
<form action={removeTodo}>
<button name="id" className="p-1 text-3xl" value={item.id}>
&times;
</button>
</form>
</li>
);
}

View file

@ -0,0 +1,6 @@
import { createClient } from "@libsql/client";
export const db = createClient({
url: process.env.TURSO_DB_URL ? process.env.TURSO_DB_URL : "file:./dev.db",
authToken: process.env.TURSO_DB_TOKEN,
});

View file

@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;

View file

@ -0,0 +1,26 @@
{
"private": true,
"scripts": {
"dev": "next dev --turbo",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@libsql/client": "0.4.0",
"next": "latest",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.1.0",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"typescript": "^5"
}
}

View file

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View file

@ -0,0 +1,13 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {},
},
plugins: [],
};
export default config;

View file

@ -0,0 +1,26 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}