Prisma 与 Zod 的类型推断

问题描述 投票:0回答:0

这是我给用户的棱镜模型

model User {
    id            String    @id @default(cuid())
    name          String?
    email         String?   @unique
    emailVerified DateTime?
    image         String?
    accounts      Account[]
    sessions      Session[]
}

我正在使用 zod-prisma 包推断类型,结果我得到以下代码

import * as z from "zod"
import { CompleteAccount, RelatedAccountModel, CompleteSession, RelatedSessionModel } from "./index"

export const UserModel = z.object({
  id: z.string(),
  name: z.string().nullish(),
  email: z.string().nullish(),
  emailVerified: z.date().nullish(),
  image: z.string().nullish(),
})

export interface CompleteUser extends z.infer<typeof UserModel> {
  accounts: CompleteAccount[]
  sessions: CompleteSession[]
}

/**
 * RelatedUserModel contains all relations on your model in addition to the scalars
 *
 * NOTE: Lazy required in case of potential circular dependencies within schema
 */
export const RelatedUserModel: z.ZodSchema<CompleteUser> = z.lazy(() => UserModel.extend({
  accounts: RelatedAccountModel.array(),
  sessions: RelatedSessionModel.array(),
}))

现在我需要使用

CompleteUser
作为发送带有
nodemailer

的电子邮件的类型
const sendWelcomeEmail = ({ email }: CompleteUser) => transporter.sendMail({
  from: `"⚡ Magic NextAuth" ${env.EMAIL_FROM}`,
  to: email,
  subject: 'Welcome to Magic NextAuth! 🎉',
  html: emailTemplate({
    base_url: env.NEXTAUTH_URL,
    support_email: '[email protected]',
  }),
}, (err, info) => {
  console.log(info);
  console.log(err);
});

我收到以下错误

Type 'string | null | undefined' is not assignable to type 'string | Address | (string | Address)[] | undefined'. Type 'null' is not assignable to type 'string | Address | (string | Address)[] | undefined'.t

这条线

to: email,

我理解类型不能是

null
。为了轻松解决这个问题,我可以使用类型
email: string
来修复它。

为了使事情变得更复杂,我必须将此功能与

next-auth
一起使用这是代码

export const authOptions: NextAuthOptions = {
  pages: {
    signIn: '/auth/signin',
    signOut: '/',
  },
  adapter: PrismaAdapter(prisma),
  providers: [
    EmailProvider({
      server: env.EMAIL_SERVER,
      from: env.EMAIL_FROM,
      maxAge: 10 * 60,
      sendVerificationRequest(params) {
        const { identifier, url, provider } = params;
        const { host } = new URL(url);
        transporter.sendMail({
          to: identifier,
          from: provider.from,
          subject: `Sign in to ${host}`,
          text: text({ url, host }),
          html: html({
            base_url: env.NEXTAUTH_URL,
            signin_url: url,
            email: identifier,
          })
        }, (err, info) => {
          console.log(info);
          console.log(err);
          const failed = info.rejected.concat(info.pending).filter(Boolean);
          if (failed.length) {
            throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`);
          }
        });
      },
    }),
  ],
  events: { createUser: sendWelcomeEmail },
  secret: env.NEXTAUTH_SECRET,
};

这一行

events: { createUser: sendWelcomeEmail },

给我以下错误

Type '(user: CompleteUser) => void & Promise<SMTPTransport.SentMessageInfo>' is not assignable to type '(message: { user: User; }) => Awaitable<void>'. Types of parameters 'user' and 'message' are incompatible. Type '{ user: User; }' is missing the following properties from type 'CompleteUser': accounts, sessions, id

不太确定如何解决它

typescript prisma nodemailer next-auth zod
© www.soinside.com 2019 - 2024. All rights reserved.