Как набирать статический тип в интерфейсе с Typescript и mongoose - PullRequest
0 голосов
/ 30 апреля 2019

Я определяю свою схему с помощью машинописного текста, и я хотел бы использовать статический метод в методе validate, предоставленном mongoose.

Я набрал следующий код, к сожалению, часть метода valide привела к краху моей сборки Typescript. Потому что он не распознает статический метод.

Я знаю, что мы не можем определить статический метод в интерфейсе, так как мне поступить в этом случае?

Спасибо заранее

import * as mongoose from 'mongoose'
import * as bcryptjs from 'bcryptjs'

const hash = bcryptjs.hash
const compare = bcryptjs.compare

export interface IUser {
  email: string,
  username: string,
  chats: number[],
  name: string,
  password: string,
  avatar: string
}

export interface IUserModel extends IUser, mongoose.Document {
  doesntExist(email?: string, username?: string): boolean,
  matchesPassword(password: string): Promise<boolean>
}

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    validate: {
      // ---- This part make my code crash
      validator: (email: string): boolean => User.doesntExist({ email }),
      message: 'Email has already been taken.'
    }
  },
  username: {
    type: String,
    validate: {
      // ---- This part make my code crash
      validator: (username: string): boolean => User.doesntExist({ username }),
      message: 'Username has already been taken.'
    }
  },
  chats: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Chat'
  }],
  name: String,
  password: String,
  avatar: String
}, {
  timestamps: true
})

userSchema.pre<IUserModel>('save', async function () {
  if (this.isModified('password')) {
    this.password = await hash(this.password, 10)
  }
})

// Check if the value don't exist in database, check unique value
userSchema.statics.doesntExist = async function (options: {email?: string, username?: string}) {
  return await this.where(options).countDocuments() === 0
}

userSchema.methods.matchesPassword = function (password: string) {
  return compare(password, this.password)
}

const User: mongoose.Model<IUserModel> = mongoose.model<IUserModel>('User', userSchema)

export default User
...