js为模型创建静电和实例函数的方式是什么? [英] What is the Nest.js way of creating static and instance functions for a model?

查看:24
本文介绍了js为模型创建静电和实例函数的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在这样的东西,或者我是否遵循标准的Mongoose程序?

我看了文档,昨天我花了一整天的时间来做这个,但是我只能找到相关的将函数放在服务组件中的文档。如果我想在服务组件(比如自定义装饰器)之外使用静电模型函数,这是不会有效的,因为DI是私有的。

我本来会在Github上创建文档请求问题,但我担心我可能忽略了什么。

编辑2:请不要更改帖子标题。"Nest"不是"Best"的拼写错误。它指的是一个名为Nest.js的Node.js框架。(请参阅帖子标签和参考文档链接)

编辑:在文档的MongoDB section中,有一段代码:

constructor(@InjectModel(CatSchema) private readonly catModel: Model<Cat>) {}
但具体地说,此Model<Cat>部分从扩展MongooseDocument接口的接口导入Cat。如果此Cat接口改为能够执行函数的类(即使在转换之后),不是更好吗?

推荐答案

我使用以下方法:

定义架构时,将静电方法添加到Mongoose架构:

UserSchema.methods.comparePassword = async function(candidatePassword: string) {
  return await bcrypt.compare(candidatePassword, this.password);
};

还将该方法包括在对象的接口定义中:

export interface User {
  firstName: string;
  ...
  comparePassword(candidatePassword: string): Promise<boolean>;
}

以及UserDocument接口

export interface UserDocument extends User, Document { }

现在我的UsersService:

export class UsersService {
  constructor(@InjectModel(Schemas.User) private readonly userRepository: Model<UserDocument>,
              private readonly walletService: WalletsService,
              @Inject(Modules.Logger) private readonly logger: Logger) {}

  async findByEmail(email: string): Promise<UserDocument> {
    return await this.userRepository.findOne({ email }).select('password');
  }
  ...
}

为了将这一切联系在一起,当用户尝试登录时,Auth服务通过id检索User对象,并调用该User对象的实例方法comparePassword:

@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
  ) { }

  async signIn({ email, password }: SignInDto): Promise<LoginResponse> {
    const user = await this.usersService.findByEmail(email);
    if (!user) { throw new UnauthorizedException('Invalid Username or Password'); }

    if (await user.comparePassword(password)) {
      const tokenPayload: JwtPayload = { userId: user.id };
      const token = this.jwtService.sign(tokenPayload);
      return ({ token, userId: user.id, status: LoginStatus.success });
    } else {
      throw new UnauthorizedException('Invalid Username or Password');
    }
  }
}

这篇关于js为模型创建静电和实例函数的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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