1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SupabaseからTypeScriptの型生成

Posted at

はじめに

この記事ではSupabaseにデータベースを作成した後、Supabase CLIを使って型定義ファイルを生成し、それをプロジェクトに統合する方法を説明します。

参考

Supabase へのログインと初期設定

まず、Supabaseにログインして初期化します

ログイン

Supabaseにログインします。

supabase login

ブラウザが開き、認証を求められます。

プロジェクトの初期化

Supabaseプロジェクトを初期化します

supabase init

型定義ファイルの生成

以下のコマンドを使用して、ファイルを生成します。

supabase gen types typescript --project-id your_project_id > database.types.ts

database.types.tsが生成されます

生成されたファイルの例

./database.types.ts
export type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[]

export interface Database {
  public: {
    Tables: {
      movies: {
        Row: {               
          id: number
          name: string
          data: Json | null
        }
        Insert: {            
          id?: never         
          name: string 
          data?: Json | null
        }
        Update: {            
          id?: never
          name?: string     
          data?: Json | null
        }
      }
    }
  }
}

createClienの使用

生成した型を使用して以下のようにcreateClient関数に型を適用します。

./index.tsx
import { createClient } from '@supabase/supabase-js'
import { Database } from './database.types'

const supabase = createClient<Database>(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_ANON_KEY
)

データの取得例

moviesテーブルからデータを取得する場合、以下のように書きます。

./index.tsx
import { createClient } from '@supabase/supabase-js'
import { Database } from './database.types'

const supabase = createClient<Database>(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_ANON_KEY
)

type Movie = Database['public']['Tables']['movies']['Row'];

// dataが型付けされる
const { data, error } = await supabase.from('movies').select('*');
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?