从数据库生成 TypeScript 类型
一个命令将您的表转换为类型。然后,您的编辑器会在运行任何操作之前拒绝错误的列或错误的值。
该页面已自动翻译。英文版具有权威性。
生成文件#
bash
npx @aurabase/gen --url https://my-app.aurabase.cloud --key "$AURABASE_SERVICE_ROLE_KEY" --out src/types/database.types.ts
架构自省 (GET /v1/db/schema) 需要 service_role 密钥 (AURABASE_SERVICE_ROLE_KEY);传递 anon 密钥会被拒绝,并显示一条显式消息。如果没有 --url 和 --key, @aurabase/gen 会从您的环境中读取 NEXT_PUBLIC_AURABASE_URL 和 AURABASE_SERVICE_ROLE_KEY 以及 .env、 .env.local、 .env.development (或带有 --from-file的本地架构快照)。
在具有两个表和两个函数的项目上,它打印:
[aurabase-gen] Types written to src/types/database.types.ts (2 table(s), 2 function(s), 0 enum(s), 0 view(s)).
每当架构发生更改时再次运行它(或在 CI 中传递 --check 以在架构漂移时失败)。添加 --schema <name> 用于除 public以外的架构,添加 --type-name 以重命名主类型,并添加 --numeric-as-string 以将 numeric/decimal 保留为 string 而不是 number。
与客户端一起使用#
typescript
import { createClient } from '@aurabase/aurabase-js'
import type { Database } from '../types/database.types'
export const aura = createClient<Database>(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!)
生成的类型使用 Row、 Insert 和 Update描述每个表。针对真实文件,编译器给出了以下结果:
typescript
const { data } = await aura.from('todos').select('id, title, done')
const title: string | undefined = data?.[0]?.title // 好的
const wrong: number | undefined = data?.[0]?.title // 错误:字符串不能分配给数字
await aura.from('todos').insert({ title: 1 }) // 错误:数字不可分配给字符串
await aura.from('todos').insert({ title: 'ok' }) // 好的:其他列都有默认值
在 Insert中,具有默认列或可为空列的列是可选的。在 Update中,每一列都是可选的。
组件的行类型#
typescript
import type { Tables, TablesInsert, TablesUpdate, Enums } from '../types/database.types'
type Todo = Tables<'todos'> // 一行,如读
type NewTodo = TablesInsert<'todos'> // insert() 接受什么
type TodoPatch = TablesUpdate<'todos'> // update() 接受什么
Enums<'name'> 给出数据库枚举的值。
检查什么#
- 不在生成文件中的表是 而不是 被拒绝:
aura.from('anything')仍然可以编译,并且其行是无类型的。 - 函数出现在带有类型化参数和返回值的
Functions下:add(a int, b int) returns int给出Args: { a: number; b: number }和Returns: number,而RETURNS TABLE (content text, dist float8)函数给出Returns: { content: string; dist: number }[]。返回匿名复合类型的函数仍显示为Record<string, unknown>。 - 检查过滤器、
insert()和update()有效负载、枚举和关系嵌入。select('a, b')字符串内的列列表用于键入结果,但拼写错误的名称仅在运行时才会被捕获(COLUMN_NOT_FOUND,带有“也许您的意思是……”提示)。 - Studio 的 类型 按钮和
npx @aurabase/gen生成相同的文件。 - 该文件反映了生成它时的架构。在您再次运行该工具之前,稍后添加的列对于类型来说是未知的。
- 架构自省需要
AURABASE_SERVICE_ROLE_KEY(在本地或在 CI 中运行;切勿提交service_role密钥或在客户端代码中公开它)。