İçeriğe geç
Aurabase Logosu
aura tabanı

Veritabanınızdan TypeScript türleri oluşturun

Tek bir komut tablolarınızı türlere dönüştürür. Editörünüz daha sonra herhangi bir şeyi çalıştırmadan önce yanlış bir sütunu veya yanlış bir değeri reddeder.

Nasıl yapılır kılavuzu8 dk. okuSeviye acemi

Bu çeviriden bu yana İngilizce kaynak değişti. Bazı bilgiler güncelliğini kaybetmiş olabilir.
Bu sayfa otomatik olarak çevrildi. İngilizce versiyonu yetkilidir.

Your tables, views, functions and enums become one TypeScript type, Database. Passed to createClient, it lets the compiler reject a wrong table, column or value before you run anything.

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

  • Node.js 20 or later for @aurabase/gen.

Reading the schema requires the service_role key: run the generators on your machine or in CI, never in a browser. The examples write types.ts, models.rs and src/types/; the Clean up block removes them.

Generate the file#

@aurabase/gen is the generator to use in an application. With version 0.7.5, create the output folder first: the published package does not create it and fails with ENOENT: no such file or directory.

mkdir -p src/types
npx @aurabase/gen --url "$NEXT_PUBLIC_AURABASE_URL" --key "$AURABASE_SERVICE_ROLE_KEY" --out src/types/database.types.ts

On the example schema it prints (measured with @aurabase/gen 0.7.5, not replayed by this page):

[aurabase-gen] ✓ Types written to src/types/database.types.ts (5 table(s), 1 function(s), 0 enum(s), 1 view(s)).

Run it again whenever the schema changes, for example after each aura db push.

Options#

OptionEnvironment variableDefaultEffect
--url <url>NEXT_PUBLIC_AURABASE_URLURL of the project
--key <key>AURABASE_SERVICE_ROLE_KEYservice_role key. An aura_anon_ or aura_auth_ key is refused before any request.
-o, --out <file>AURABASE_TYPES_OUTStandard outputFile to write
-s, --schema <name>AURABASE_SCHEMApublicName of the schema key inside Database (Database['public'])
-t, --type-name <name>DatabaseName of the main type
--numeric-as-stringOffnumeric and decimal become string instead of number, to keep their precision
--allow-emptyOffWrite the file even if a table has no column (a MongoDB project); without it, the command fails
--checkOffCompare with the --out file instead of writing it (Check the types in CI)
-h, --help, -v, --versionHelp and version

Without --url and --key, the variables are read from the environment, then from .env.local, .env.development.local, .env.development and .env in the current folder, in this order; a variable already set wins.

With the CLI or the API#

aura db generate asks the project for its types (GET /v1/db/{project_id}/types.ts) and writes them to types.ts in the current folder:

aura db generate > /dev/null
sed -n '/^      todos: {/,/^        Relationships/p' types.ts
      todos: {
        Row: {
          id: number;
          user_id: string;
          title: string;
          done: boolean;
          created_at: string;
        };
        Insert: {
          id?: number;
          user_id: string;
          title: string;
          done?: boolean;
          created_at?: string;
        };
        Update: {
          id?: number;
          user_id?: string;
          title?: string;
          done?: boolean;
          created_at?: string;
        };
        Relationships: [];

The route can be called directly with the service_role key; the anon key is refused:

curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -c '^export'
curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_ANON_KEY" | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).error.message'
26
Forbidden: DDL operation is reserved to the service_role role

aura db generate --lang rust writes models.rs, one struct per table, from the same schema; nullable columns become Option<…> and enums become Rust enums:

aura db generate --lang rust > /dev/null
sed -n '/^pub struct Todos/,/^}/p' models.rs
pub struct Todos {
    pub id: i64,
    pub user_id: String,
    pub title: String,
    pub done: bool,
    pub created_at: String,
}
@aurabase/genaura db generate
OutputThe file you choose, or standard outputtypes.ts in the current folder
Database typeSame tables, views, functions and enumsSame
HelpersTables, TablesInsert, TablesUpdate, EnumsTables, TablesInsert, TablesUpdate, an interface per table (Todos, TodosInsert…), TableName
OptionsAll the options above--lang ts (default) or rust
Drift check--checkNone

Without a linked project, aura db generate reads the database of DATABASE_URL with a simpler generator (Local development). aura db watch regenerates types.ts after each push (Push, pull, diff and watch).

What the file contains#

Part of Database['public']FromContents
TablesEach tableRow (a read row), Insert (optional when the column has a default, is nullable or is an identity), Update (all optional), Relationships (foreign keys)
ViewsEach viewRow only, every column nullable
FunctionsEach functionArgs (argument names and types) and Returns; a returns table (…) function gives an array of rows
EnumsEach enum typeThe union of its values, such as 'todo' | 'doing' | 'done'
CompositeTypesAlways empty

Types follow the JSON the API returns: integers and float give number, numeric gives number (or string with --numeric-as-string), uuid, dates and timestamps give string, json and jsonb give Json, arrays give arrays, bigint gives number.

Use it with the client#

Excerpt of src/lib/aurabase.ts:

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 types for your components#

import type { Tables, TablesInsert, TablesUpdate, Enums } from '../types/database.types'

type Todo = Tables<'todos'>             // a row, as read
type NewTodo = TablesInsert<'todos'>    // what insert() accepts
type TodoPatch = TablesUpdate<'todos'>  // what update() accepts

Tables<'open_todos'> gives the row of a view, and Enums<'name'> the values of an enum.

What is checked#

Checked with TypeScript 5.9.3, @aurabase/aurabase-js 0.7.5 and a file generated from the example schema (not replayed by this page):

const { data } = await aura.from('todos').select('id, title, done')
const title: string | undefined = data?.[0]?.title    // ok
const wrong: number | undefined = data?.[0]?.title    // error: string is not assignable to number

await aura.from('todos').insert({ title: 1 })          // error: number is not assignable to string
await aura.from('todos').insert({ title: 'ok', user_id: userId }) // ok: the other columns have defaults
await aura.from('todos').update({ done: 'yes' })       // error: string is not assignable to boolean
await aura.from('todos').select('id').eq('done', 'no') // error: string is not assignable to boolean
await aura.from('anything').select('id')               // error: no overload matches this call
await aura.from('open_todos').insert({ title: 'x' })   // error: a view has no Insert type

const typo = await aura.from('todos').select('id, titel')
typo.data?.[0]?.id // error: column 'titel' does not exist on 'todos'
  • Tables and views. A name that is not in the file is rejected. A view can be read, not written.
  • Columns in select('…'). The string is parsed: a misspelled column turns the row type into an error that names the column, as soon as you use the row.
  • Values. insert(), update() and filters such as eq() are checked against the column types. In Insert, a column without a default that is not nullable is required: todos.user_id here.
  • Relationships. An embed such as select('role, orgs(name)') is typed from Relationships.
  • Functions. aura.rpc() does not use the Functions part of the file: its arguments are not checked and its data is unknown. Type the result yourself.
  • Freshness. The file describes the schema at the time you generated it: regenerate it after each migration, and check it in CI.

Check the types in CI#

--check regenerates the file in memory and compares it with --out. It exits with 0 and [aurabase-gen] ✓ src/types/database.types.ts is up to date. when they match, and with 1 and [aurabase-gen] Types in src/types/database.types.ts are out of date. Re-run aurabase-gen without --check. when the schema changed and the committed file was not regenerated. Excerpt of a CI step (not replayed here):

      - run: npx @aurabase/[email protected] --check --out src/types/database.types.ts
        env:
          NEXT_PUBLIC_AURABASE_URL: ${{ vars.PROJECT_URL }}
          AURABASE_SERVICE_ROLE_KEY: ${{ secrets.SERVICE_ROLE_KEY }}

Run it after aura db push in the same job, so that the types are compared with the migrated schema.

Common errors#

MessageCauseFix
[aurabase-gen] ENOENT: no such file or directory, open '…'The folder of --out does not exist (@aurabase/gen 0.7.5).mkdir -p the folder first.
[aurabase-gen] Error: the project URL and/or service_role key is missing.Neither the options nor the variables are set.Pass --url and --key, or set the variables.
[aurabase-gen] Error: schema introspection requires a service_role key (aura_sk_...), not an anon/auth key.An anon or authenticated key was passed.Use the service_role key.
[aurabase-gen] Types in … are out of date. Re-run aurabase-gen without --check.The schema changed since the file was generated.Regenerate and commit the file.
[aurabase-gen] Tables without any column: … Use --allow-empty to generate anyway.A MongoDB project, whose collections have no declared columns.Add --allow-empty, knowing these types check nothing.
API failed to generate types (403 Forbidden): …aura db generate with a key that is not service_role.Export the service_role key.

Clean up#

rm -f types.ts models.rs
rm -rf src/types

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Bir sorunu bildirin