跳至内容
从 NextAuth.js v4 迁移?阅读 我们的迁移指南.

MikroORM 适配器

资源

设置

安装

npm install @mikro-orm/core @auth/mikro-orm-adapter

环境变量

DATABASE_CONNECTION_STRING=./db.sqlite

配置

./auth.ts
import NextAuth from "next-auth"
import { MikroOrmAdapter } from "@auth/mikro-orm-adapter"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: MikroOrmAdapter({
    // MikroORM options object - https://mikro-orm.io/docs/next/configuration#driver
    dbName: process.env.DATABASE_CONNECTION_STRING,
    type: "sqlite",
    debug: true,
  }),
  providers: [],
})

高级用法

传递自定义实体

MikroORM 适配器附带自己的实体集。如果您想扩展它们,可以选择将它们传递给适配器。

此模式适用于 MikroORM 中使用,并且基于我们的主模式 模式

./auth.ts
import config from "config/mikro-orm.ts"
import {
  Cascade,
  Collection,
  Entity,
  OneToMany,
  PrimaryKey,
  Property,
  Unique,
} from "@mikro-orm/core"
import { defaultEntities } from "@auth/mikro-orm-adapter"
 
const type { Account, Session } = defaultEntities
 
@Entity()
export class User implements defaultEntities.User {
  @PrimaryKey()
  id: string = randomUUID()
 
  @Property({ nullable: true })
  name?: string
 
  @Property({ nullable: true })
  @Unique()
  email?: string
 
  @Property({ type: "Date", nullable: true })
  emailVerified: Date | null = null
 
  @Property({ nullable: true })
  image?: string
 
  @OneToMany({
    entity: () => Session,
    mappedBy: (session) => session.user,
    hidden: true,
    orphanRemoval: true,
    cascade: [Cascade.ALL],
  })
  sessions = new Collection<Session>(this)
 
  @OneToMany({
    entity: () => Account,
    mappedBy: (account) => account.user,
    hidden: true,
    orphanRemoval: true,
    cascade: [Cascade.ALL],
  })
  accounts = new Collection<Account>(this)
 
  @Enum({ hidden: true })
  role = "ADMIN"
}
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: MikroOrmAdapter(config, { entities: { User } }),
})

包含默认实体

您可能希望在 MikroORM 配置中包含 defaultEntities 以将其包含在迁移等中。

要实现这一点,请将它们包含在您的“实体”数组中

config/mikro-orm.ts
import { Options } from "@mikro-orm/core"
import { defaultEntities } from "@auth/mikro-orm-adapter"
 
const config: Options = {
  entities: [VeryImportantEntity, ...Object.values(defaultEntities)],
}
 
export default config
Auth.js © Balázs Orbán 和团队 -2024