生成类型
Supabase将很快发布本地类型生成器,为各种语言转储你的数据库类型。目前,我们通过一个第三方工具支持TypeScript。
使用TypeScript
supabase-js
带有类型定义,可与TypeScript一起使用,方便IntelliSense自动完成和编辑器中的文档。
当使用TypeScript时,你可以将数据库行的类型作为一个类型参数传递给from
方法,以获得更好的自动完成支持。
如果你没有提供行的类型,你需要明确传递from<any>('tableName')
。
type Message = {
id: number;
inserted_at: string;
message: string;
user_id: string;
channel_id: number;
author: { username: string };
}
const response = await supabase
.from<Message>('messages') // Message maps to the type of the row in your database.
.select('*, author:user_id(username)')
.match({ channel_id: 2 }) // Your IDE will be able to help with auto-completion.
response.data // Response data will be of type Array<Message>.
// If you don't provide a type for the row you need to explicitly pass `from<any>('tableName')`.
const response = await supabase
.from<any>('messages')
.select('*, author:user_id(username)')
.match({ channel_id: 2 })
response.data // Response data will be of type Array<any>.
从OpenAPI规范中生成数据库类型
Supabase 会为你的数据库生成一个 OpenAPI 规范文件,该文件可用于生成你的数据类型,以便与 TypeScript 一起使用。
你的Supabase项目的OpenAPI规范可以通过以下方式访问。
https://your-project.supabase.co/rest/v1/?apikey=your-anon-key
使用开源工具openapi-typescript你可以生成本地自定义类型:
npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/supabase.ts
重要提示:
- 由于生成器使用JSON API,没有办法确定一个列是否是数组。它将把数组类型生成为 "string",尽管Supabase自动处理并返回数组。
你可以在文件中通过改变类型来手动解决这个问题,例如,
names: string
->names: string[]
。 - 这些类型不会自动与你的数据库保持同步,所以确保在你对数据库进行修改后重新生成你的类型。
在你生成了你的类型之后,你可以在你的TypeScript项目中使用它们:
import { NextApiRequest, NextApiResponse } from "next";
import { createClient } from "@supabase/supabase-js";
import { definitions } from "../../types/supabase";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.SUPABASE_SECRET_KEY
);
export default async (req: NextApiRequest, res: NextApiResponse) => {
const allOnlineUsers = await supabase
.from<definitions["users"]>("users")
.select("*")
.eq("status", "ONLINE");
res.status(200).json(allOnlineUsers);
};
通过GitHub Actions自动更新类型
让你的类型定义与数据库保持同步的一个方法是设置一个按时间表运行的GitHub Actions。
在你的package.json中添加一个脚本来生成类型。
"update-types": "npx openapi-typescript https://your-project.supabase.co/rest/v1/?apikey=your-anon-key --output types/database/index.ts"
在你的 repo 中,创建文件 .github/workflows/update-types.yml
。在这个文件中添加以下片段来定义动作。如果你的定义有变化,这个脚本将提交变化到你的 repo。
name: Update database types
on:
schedule:
# sets the action to run daily. You can modify this to run the action more or less freqently
- cron: '0 0 * * *'
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
persist-credentials: false
fetch-depth: 0
- uses: actions/setup-node@v2.1.5
with:
node-version: 14
- run: npm run update-types
- name: check for file changes
id: git_status
run: |
echo "::set-output name=status::$(git status -s)"
- name: Commit files
if: ${ {contains(steps.git_status.outputs.status, ' ')} }
run: |
git add types/database/index.ts
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "Update database types" -a
- name: Push changes
if: ${ {contains(steps.git_status.outputs.status, ' ')} }
uses: ad-m/github-push-action@master
with:
github_token: $
branch: $