Drizzle ORM 轉接器
資源
設定
安裝
npm install drizzle-orm @auth/drizzle-adapter
npm install drizzle-kit --save-dev
環境變數
AUTH_DRIZZLE_URL=postgres://postgres:postgres@127.0.0.1:5432/db
組態
若要使用此轉接器,您必須在專案中設定 Drizzle ORM 和 Drizzle Kit。Drizzle 提供一個簡單的快速入門指南。如需更多詳細資訊,請參閱 Drizzle 關於您各自資料庫的文件(PostgreSQL、MySQL 或 SQLite)。總而言之,該設定應該如下所示。
- 根據以下其中一個,建立您的結構描述檔案。
- 在您的專案中安裝一個支援的資料庫驅動程式,例如
@libsql/client
、mysql2
或postgres
。 - 建立一個
drizzle.config.ts
檔案。 - 使用類似
drizzle-kit generate:pg
的指令,從您的結構描述檔案產生初始遷移。 - 透過使用
migrate()
函式來套用遷移,或使用類似drizzle-kit push:pg
的指令直接將變更推送到您的資料庫。 - 如果您的結構描述與預設的不同,請將它們作為第二個參數傳遞給轉接器。
結構描述
轉接器設定
./auth.ts
import NextAuth from "next-auth"
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import { db } from "./schema.ts"
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: DrizzleAdapter(db),
providers: [],
})
傳遞您自己的結構描述
如果您想使用自己的表格,您可以將它們作為第二個引數傳遞給 DrizzleAdapter
。
sessionsTable
是可選的,只有在使用資料庫工作階段策略時才需要。verificationTokensTable
是可選的,只有在使用魔法連結供應商時才需要。
auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import { db, accounts, sessions, users, verificationTokens } from "./schema"
export const { handlers, auth } = NextAuth({
adapter: DrizzleAdapter(db, {
usersTable: users,
accountsTable: accounts,
sessionsTable: sessions,
verificationTokensTable: verificationTokens,
}),
providers: [Google],
})
遷移您的資料庫
現在您的結構描述已在您的程式碼中描述,您需要將您的資料庫遷移到您的結構描述。範例 migrate.ts
檔案如下所示。如需更多資訊,請參閱 Drizzle 的遷移快速入門指南。
migrate.ts
import "dotenv/config"
import { migrate } from "drizzle-orm/mysql2/migrator"
import { db, connection } from "./db"
// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" })
// Don't forget to close the connection, otherwise the script will hang
await connection.end()
有關如何使用 Drizzle 管理遷移的完整文件,請參閱 Drizzle Kit 遷移頁面。