Sequelize 适配器
资源
设置
安装
npm install @auth/sequelize-adapter sequelize
环境变量
DATABASE_URL=postgres://postgres:[email protected]:5432/db
配置
⚠️
您还需要手动安装您选择的数据库驱动程序。
./auth.ts
import NextAuth from "next-auth"
import SequelizeAdapter from "@auth/sequelize-adapter"
import { Sequelize } from "sequelize"
const sequelize = new Sequelize(process.env.DATABASE_URL)
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [],
adapter: SequelizeAdapter(sequelize),
})
模式
默认情况下,sequelize 适配器不会在您的数据库中创建表格。在生产环境中,最佳实践是使用迁移在您的数据库中创建必需的表格。在开发环境中,您可以调用sequelize.sync()
让 sequelize 创建必要的表格、外键和索引
此模式适合在 Sequelize 中使用,并基于我们的主要模式
./auth.ts
import NextAuth from "next-auth"
import SequelizeAdapter from "@auth/sequelize-adapter"
import Sequelize from "sequelize"
const sequelize = new Sequelize("sqlite::memory:")
const adapter = SequelizeAdapter(sequelize)
// Calling sync() is not recommended in production
sequelize.sync()
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter,
})
高级用法
使用自定义模型
Sequelize 模型可以像这样自定义
./auth.ts
import NextAuth from "next-auth"
import SequelizeAdapter, { models } from "@auth/sequelize-adapter"
import Sequelize, { DataTypes } from "sequelize"
const sequelize = new Sequelize("sqlite::memory:")
export const { handlers, auth, signIn, signOut } = NextAuth({
// https://authjs.oauth.ac.cn/reference/providers/
providers: [],
adapter: SequelizeAdapter(sequelize, {
models: {
User: sequelize.define("user", {
...models.User,
phoneNumber: DataTypes.STRING,
}),
},
}),
})