इसे छोड़कर कंटेंट पर जाएं

Turso & Astro

यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।

Turso is a distributed database built on libSQL, a fork of SQLite. It is optimized for low query latency, making it suitable for global applications.

  • The Turso CLI installed and signed in
  • A Turso Database with schema
  • Your Database URL
  • An Access Token

Configure environment variables

Section titled Configure environment variables

Obtain your database URL using the following command:

Terminal window
turso db show <database-name> --url

Create an auth token for the database:

Terminal window
turso db tokens create <database-name>

Add the output from both commands above into your .env file at the root of your project. If this file does not exist, create one.

.env
TURSO_DATABASE_URL=libsql://...
TURSO_AUTH_TOKEN=

Install the @libsql/client to connect Turso to Astro:

Terminal window
npm install @libsql/client

Create a file turso.ts in the src folder and invoke createClient, passing it TURSO_DATABASE_URL and TURSO_AUTH_TOKEN:

src/turso.ts
import { createClient } from "@libsql/client/web";
export const turso = createClient({
url: import.meta.env.TURSO_DATABASE_URL,
authToken: import.meta.env.TURSO_AUTH_TOKEN,
});

To access information from your database, import turso and execute a SQL query inside any .astro component.

The following example fetches all posts from your table, then displays a list of titles in a <BlogIndex /> component:

src/components/BlogIndex.astro
---
import { turso } from '../turso'
const { rows } = await turso.execute('SELECT * FROM posts')
---
<ul>
{rows.map((post) => (
<li>{post.title}</li>
))}
</ul>

The execute() method can take an object to pass variables to the SQL statement, such as slug, or pagination.

The following example fetches a single entry from the posts table WHERE the slug is the retrieved value from Astro.params, then displays the title of the post.

src/pages/index.astro
---
import { turso } from '../turso'
const { slug } = Astro.params
const { rows } = await turso.execute({
sql: 'SELECT * FROM posts WHERE slug = ?',
args: [slug!]
})
---
<h1>{rows[0].title}</h1>

अधिक बैकएंड सेवा मार्गदर्शिकाएँ