如何使用猫鼬的打字稿创建自定义架构类型

时间:2018-07-24 22:15:49

标签: typescript mongoose

我正在设置一个原理图类型,以了解它如何与打字稿和猫鼬一起工作。该示例使用简单的正则表达式验证电子邮件,但我不知道如何将其注入mongoose.d.ts

的声明中。

这怎么工作?

email.ts

import * as mongoose from 'mongoose'

function Email (path: any, options: any[]) {
  mongoose.SchemaType.call(this, path, options, 'Email')
}

Email.prototype = Object.create(mongoose.SchemaType.prototype)

Email.prototype.cast = function (email: string) {
  if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
    throw new Error('Invalid email address')
  }
  return email
}

// Typescript: Property 'Email' does not exist on type 'typeof Types'.
mongoose.Schema.Types.Email = Email

email.d.ts

declare module 'mongoose' {
  namespace Schema {
    namespace Types {
      // ???
    }
  }
}

我想在计划中得到这个结果

const schema: mongoose.Schema = new mongoose.Schema({
  email: {
    type: Email
  }
})

2 个答案:

答案 0 :(得分:1)

我终于做到了,我做了一个功能,但我想我可以改善! :)

index.d.ts

declare module 'mongoose' {
  namespace Schema {
    namespace Types {
      function Email (path: string, options: any): void
    }
  }
}

email.ts

import * as mongoose from 'mongoose'

function Email (path: string, options: any): void {
  mongoose.SchemaTypes.String.call(this, path, options)

  function isValid (val) {
    // validation logic
  }

  this.validate(isValid, options.message || 'invalid email address')
}

Object.setPrototypeOf(Email.prototype, mongoose.SchemaTypes.String.prototype)

mongoose.Types.Email = Email
mongoose.SchemaTypes.Email = Email

答案 1 :(得分:0)

email.ts

import mongoose from 'mongoose';

export default class Email extends mongoose.SchemaType {
    cast(email: string) {
        if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
            throw new Error('Invalid email address')
        }
        return email
    }
}

mongoose.Schema.Types.Email = Email;

index.d.ts

declare module 'mongoose' {
    namespace Schema {
        namespace Types {
            class Email extends SchemaType {}
        }
    }
}