打字稿扩展模块(增强)

时间:2019-01-27 14:52:01

标签: node.js typescript mongoose

我想用自己的类和函数扩展已安装的模块(猫鼬)。 我写了函数和类,它们工作正常。

现在,我想将它们添加到mongoose模块中。 所以我现在有了这个文件: mongoInstance.ts

import * as mg from 'mongoose'

class _Schema extends mg.Schema {
    constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions) {
        super(definition, options)
        this.addData()
    }
    private addData() {
        //do stuff
    }
}  

function _limitedRequest(schema: mg.Schema, options = 200) {
    schema.pre("find", function (next) {
        this.limit(options)
        next()
    })
}

declare module 'mongoose' {
    export class _Schema extends Schema {
        constructor(definition?: SchemaDefinition, options?: SchemaOptions)
        private addData(): void
    }
    export function _limitedRequest(schema: Schema, options?: number): void
}

现在我可以在我的应用中的任何地方做

otherFile.ts

import * as mg from 'mongoose'
//doesnt work
var test1= new mg._Schema({})
//works
var test2= new mg.Schema({})

因此VSCode向我推荐了我的课程,并且IntellIsense可以工作。但是似乎没有该类的实现。 Webpack在将代码编译到bundle.js时不会引发任何错误,但是当我尝试使用node bundle.js运行bundle.js时,它说: TypeError:mg._Schema不是构造函数

2 个答案:

答案 0 :(得分:1)

您将需要两件事:

  1. 使用声明文件扩展SELECT *, ( SELECT SUM(records.amount) AS total_income FROM records WHERE records.category = "income", records.date BETWEEN DATE("now", "start of month") AND DATE("now", "start of month", "+1 month", "-1 day") ), ( SELECT SUM(records.amount) AS total_expense FROM records WHERE records.category = "expense", records.date BETWEEN DATE("now", "start of month") AND DATE("now", "start of month", "+1 month", "-1 day") ) FROM accounts INNER JOIN records ON accounts.id = records.accountId; 的类型定义。
  2. 添加功能,以便模块匹配其新定义。

mongoose

创建一个声明文件(mongoose.d.ts)并将其包含在您的项目中。

*.d.ts

import * as mg from 'mongoose'; declare module 'mongoose' { export class _Schema extends mg.Schema { constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions); } export function _limitedRequest(schema: mg.Schema, options: number): void; }

添加刚刚声明的功能。

mongoose-instance.ts

import mg from 'mongoose'; mg._Schema = class extends mg.Schema { constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions) { super(definition, options) this.addData() } private addData() { //do stuff } } mg._limitedRequest = function _limitedRequest(schema: mg.Schema, options = 200) { schema.pre("find", function (next) { this.limit(options) next() }) } export default mg;

从现在开始,使用您的consumer.ts的本地版本。

mongoose

如果遇到与默认导入有关的任何问题,请确保在import mongoose from '../path/to/mongoose-instance'; console.log(mongoose._Schema); 中启用以下两个标志:tsconfig.jsonallowSyntheticDefaultImports

答案 1 :(得分:0)

在mongoInstance.ts中将其导入:

import mongoose from "mongoose";

在mongoInstance.ts中导出类

export class _Schema extends mg.Schema { ...

在您的otherFile.ts

import { _Schema} from "./otherFile";