TypeORM 条件可空? [英] TypeORM conditional nullable?

查看:63
本文介绍了TypeORM 条件可空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TypeORM 和 Postgres 在 NestJS 中开发登录系统.在我的登录选项中,我建议用户使用几个电子邮件/密码或使用 OAuth 身份验证.但是,一旦创建了帐户,它们就不会相互排斥(例如,用户可以将电子邮件 + 密码和 Google 帐户附加到他的帐户).

I am developing a log in system in NestJS using TypeORM and Postgres. In my login options, I propose the user to use a couple email / password or to use an OAuth authentication. But once an account is created, they are not mutually exclusive (a user can have an email + password and a Google account attached to his account, for example).

因此,我想让密码或 OAuthLogin 可以为空,但至少其中之一永远不能为空.

Therefore, I would like to make the password OR the OAuthLogin nullable, but at least one of them should never be nullable.

是否可以通过 TypeORM 实现这一点?

Is it possible to achieve this with TypeORM ?

@Entity()
class User {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column({ unique: true })
    public email: string;

    @Column({ nullable: true })
    @Exclude()
    public password?: string;

    @JoinColumn()
    @OneToMany(() => OAuthLogin, (provider: OAuthLogin) => provider.user, {
        cascade: true,
    })
    public oAuthLogins: OAuthLogin[];
}

export default User;

(P.S.:对于我当前的代码,我选择使密码只能为空...)

(P. S.: for my current code, I chose to make the password only nullable...)

推荐答案

简短的回答是否定的,不是在 TypeORM 级别.但是,您可以使用 ValidateIf 在您的应用程序代码中实现这一点 来自 class-validator 的装饰器:

The short answer is no, not at the TypeORM level. However, you can achieve this in your application code using the ValidateIf decorator from class-validator:

@Column({ nullable: true })
@Exclude()
@IsNotEmpty()
@ValidateIf(u => !u.oAuthLogins || u.oAuthLogins.length === 0)
public password?: string;

@JoinColumn()
@IsArray()
@ValidateIf(u => !u.password)
@OneToMany(() => OAuthLogin, (provider: OAuthLogin) => provider.user, {
cascade: true,
})
public oAuthLogins?: OAuthLogin[];

在您的应用程序中的其他地方:

Elsewhere in your application:

import { validate } from 'class-validator';
...
validate(user)

如果该实体跨越控制器,您还可以使用 NestJS 的 ValidationPipe在控制器或应用程序级别强制执行此操作:

If this entity is crossing a controller, you can also use NestJS's ValidationPipe to enforce this at the controller or application level:

// main.ts
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

这篇关于TypeORM 条件可空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆