Prisma schemeから型を生成してNext.jsで使う
はじめに
Next.js でいわゆるフルスタックな開発をしようとしていたときに、Prisma scheme から型を生成したときのメモ
セットアップ
create-next-app
を使って Next.js のプロジェクトを生成します。
npx create-next-app webapp --ts --tailwind --eslint --app --src-dir --use-npm ✔ Would you like to customize the default import alias? … No / Yes
Prisma のセットアップをします。データソースは何でもいいですが sqlite にしました。
cd webapp npx prisma init --datasource-provider sqlite
prisma init
によって prisma
ディレクトリと scheme.prisma
ファイルが生成されます。
生成されたファイルに generator zod
とモデルを追加します。
// This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" } datasource db { provider = "sqlite" url = env("DATABASE_URL") } generator zod { provider = "zod-prisma-types" } model User { id Int @id @default(autoincrement()) name String }
Prisma ではジェネレーターによって、データモデルから何かしらを出力することができます。今回は zod-prisma-types を指定してデータモデルから、TypeScriptの型を出力させます。
次に、定義したスキーマからデータベースを生成します。
npm install -D zod-prisma-types npx prisma migrate dev --name init
これで sqlite のデータベースと zod による型定義が出力されます。
prisma ├── dev.db ├── dev.db-journal ├── generated │ └── zod │ └── index.ts ├── migrations │ ├── 20230515191627_init │ │ └── migration.sql │ └── migration_lock.toml └── schema.prisma
型定義へのエイリアスを tsconfig に追加
paths
に @/prisma-types
で参照先のエイリアスを追加します。
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"], "@/prisma-types": ["./prisma/generated/zod/index.ts"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] }
これで生成した型定義を、Next.js 側の実装で楽に使える。