Skip to content

萨塔与 Astro

萨塔 是一个无服务器数据平台,通过公开单个一致的 REST API,结合了关系数据库、搜索引擎和分析引擎的功能。

¥Xata is a Serverless Data Platform that combines the features of a relational database, a search engine, and an analytics engine by exposing a single consistent REST API.

¥Adding a database with Xata

¥Prerequisites

  • 已创建数据库的 萨塔 账户。(你可以从 Web UI 使用示例数据库。)

  • 访问令牌 (XATA_TOKEN_API)。

  • 你的数据库 URL。

更新并初始化 Xata CLI 后,你将在 .env 文件和定义的数据库 URL 中拥有 API 令牌。

¥After you update and initialize the Xata CLI, you will have your API token in your .env file and database URL defined.

设置结束时,你应该拥有:

¥By the end of the setup, you should have:

.env
XATA_API_KEY=hash_key
# Xata branch that will be used
# if there's not a xata branch with
# the same name as your git branch
XATA_BRANCH=main

databaseURL 定义:

¥And the databaseURL defined:

.xatarc
{
"databaseUrl": "https://your-database-url"
}

¥Environment configuration

要为环境变量提供 IntelliSense 和类型安全,请在 src/ 目录中编辑或创建文件 env.d.ts

¥To have IntelliSense and type safety for your environment variables, edit or create the file env.d.ts in your src/ directory:

src/env.d.ts
interface ImportMetaEnv {
readonly XATA_API_KEY: string;
readonly XATA_BRANCH?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

使用 Xata CLI 中的代码生成并选择 TypeScript 选项,为你生成了 SDK 的实例,其中的类型适合你的数据库架构。此外,@xata.io/client 已添加到你的 package.json 中。

¥Using the codegeneration from the Xata CLI and choosing the TypeScript option, generated an instance of the SDK for you, with types tailored to your database schema. Additionally, @xata.io/client was added to your package.json.

你的 Xata 环境变量和数据库 URL 已由 SDK 实例自动拉取,因此无需进行更多设置工作。

¥Your Xata environment variables and database url were automatically pulled by the SDK instance, so there’s no more setup work needed.

现在,你的项目应该具有以下结构:

¥Now, your project should have the following structure:

  • Directorysrc/
    • xata.ts
    • env.d.ts
  • .env
  • astro.config.mjs
  • package.json
  • .xatarc

¥Create your queries

要查询你的帖子,请在 .astro 文件中导入并使用 XataClient 类。下面的示例查询 Xata 示例博客数据库中的前 50 篇帖子。

¥To query your posts, import and use XataClient class in a .astro file. The example below queries the first 50 posts from Xata’s Sample Blog Database.

src/pages/blog/index.astro
---
import { XataClient } from '../../xata';
const xata = new XataClient({
apiKey: import.meta.env.XATA_API_KEY,
branch: import.meta.env.XATA_BRANCH
});
const { records } = await xata.db.Posts.getPaginated({
pagination: {
size: 50
}
})
---
<ul>
{records.map((post) => (
<li>{post.title}</li>
))}
</ul>

请务必注意,每次架构更改时都需要重新生成 SDK。因此,请避免更改 Xata CLI 创建的生成文件,因为一旦架构更新,你的更改将被覆盖。

¥It’s important to note the SDK needs to be regenerated everytime your schema changes. So, avoid making changes to the generated files the Xata CLI creates because once schema updates, your changes will be overwritten.

¥Official Resources

More backend service guides

Astro 中文网 - 粤ICP备13048890号