首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打字机上的TypeGraphql - @inputtype

打字机上的TypeGraphql - @inputtype
EN

Stack Overflow用户
提问于 2020-06-04 22:55:31
回答 2查看 942关注 0票数 1

你好,我需要检查一下数据库中是否已经有电子邮件:

在这方面:

代码语言:javascript
复制
return User.findOne({ where: { email } }).then((user) => {
  if (user) return false;
  return true;
});

我有以下输入类型:

代码语言:javascript
复制
@InputType()
export class RegisterInput {
  @Field()
  @IsEmail({}, { message: 'Invalid email' })
  email: string;

  @Field()
  @Length(1, 255)
  name: string;

  @Field()
  password: string;
}

我想知道是否有任何方法来验证输入类型中的电子邮件?或者只是我的决心:

代码语言:javascript
复制
@Mutation(() => User)
  async register(
    @Arg('data')
    { email, name, password }: RegisterInput,
  ): Promise<User> {
    const hashedPassword = await bcrypt.hash(password, 12);

    const user = await User.create({
      email,
      name,
      password: hashedPassword,
    }).save();

    return user;
  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-07 21:29:32

实际上,您可以为class-validator注册自己的装饰师。

例如,它可以如下所示:

isEmailAlreadyExists.ts

代码语言:javascript
复制
import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';
import { UserRepo } from '../../repositories/UserRepo';
import { InjectRepository } from 'typeorm-typedi-extensions';

@ValidatorConstraint({ async: true })
export class isEmailAlreadyExist
  implements ValidatorConstraintInterface {
  @InjectRepository()
  private readonly userRepo: UserRepo;

  async validate(email: string) {
    const user = await this.userRepo.findOne({ where: { email } });

    if (user) return false;
    return true;
  }
}

export function IsEmailAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: isEmailAlreadyExist,
    });
  };
}

如果您正在注入依赖项,那么您也应该在class-validator中注入它。只需将以下内容添加到主文件中:

代码语言:javascript
复制
import { Container } from 'typedi';
import * as classValidator from 'class-validator';

classValidator.useContainer(Container);

...
const schema = await buildSchema({
    resolvers: [...],
    container: Container,
  });

然后您可以在您的InputType中使用装饰器。

代码语言:javascript
复制
import { InputType, Field } from 'type-graphql';
import { IsEmailAlreadyExist } from '../../../utils/validators/isEmailAlreadyExist';

@InputType()
export class YourInput {
  @Field()
  @IsEmailAlreadyExist()
  email: string;
}
票数 1
EN

Stack Overflow用户

发布于 2020-06-07 21:14:33

其实我自己也是为了我自己的项目才想出来的。

您可以通过RegisterInput参数对电子邮件添加一个验证,如果电子邮件已经存在,则抛出一个错误。

代码语言:javascript
复制
import { Repository } from 'typeorm'
import { InjectRepository } from 'typeorm-typedi-extensions'

...

// Use dependency injection in the resolver's constructor
constructor(
  @InjectRepository(User) private readonly userRepository: Repository<User>
) {}

...

// Your mutation
@Mutation(() => User)
async register(
  @Arg('data')
  { email, name, password }: RegisterInput,
): Promise<User> {
  const hashedPassword = await bcrypt.hash(password, 12);

  const userWithEmail = this.userRepository.find({ email: email })

  // If a user with the email was found
  if (userWithEmail) {
    throw new Error('A user with that email already exists!')
  }

  const user = await User.create({
    email,
    name,
    password: hashedPassword,
  }).save();

  return user;
}

要使用InjectRepository,请确保将“容器”添加到buildSchema函数中:

代码语言:javascript
复制
import { Container } from 'typedi'
...
const schema = await buildSchema({
  resolvers: [...],
  container: Container
})

如果这件事对你有用,请告诉我?谢谢!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62205487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档