node.js - 使用不同的参数类型制作分页功能
问题描述
我是 typescript 的新手,在我的 Nodejs 应用程序中,我创建了一个中间件来对传入的对象数组进行分页。
我有时希望这个数组是 mongoose 类型Model
,但我也希望它能够包含一个普通的对象数组。
到目前为止,这是我的代码:
import { Request, Response, NextFunction } from 'express';
import expressAsyncHandler from 'express-async-handler';
import { Model } from 'mongoose';
const paginate = function <M>(model: Model<M>) {
return expressAsyncHandler(async function (
req: Request,
res: Response,
next: NextFunction
) {
try {
const modelArray = await model.find({});
/// ...rest of the code..
}
catch(err){
// ....
}
});
};
我这样称呼它:
router.get('/',paginate(Category), getAllCategories);
因此,当paginate
接收到一个 Category
- 这是一个 Mongoose 模型时,它会将类型分配给model
分页内的参数。
如果我想用不同的数据调用分页怎么办?如果你使用 {[a:1],[b:2]} 会怎样?
import { Request, Response, NextFunction } from 'express';
import expressAsyncHandler from 'express-async-handler';
import { Model } from 'mongoose';
type IAgrs<Type> = Record<string, unknown>[] | Model<Type>;
const paginate = function <M>(model: IAgrs<M>) {
return expressAsyncHandler(async function (
req: Request,
res: Response,
next: NextFunction
) {
try {
const modelArray = await model.find({});
/// ...rest of the code..
}
catch(err){
// ....
}
});
};
我知道调用find({})
将{[a:1],[b:2]}
解决错误,但我收到的错误对我来说并不清楚,原因find
是Array
原型上的方法,我告诉 Typescriptmodel
可以是 Array 类型。
This expression is not callable. Each member of the union type '{ <S extends Record<string, unknown>>(predicate: (this: void, value: Record<string, unknown>, index: number, obj: Record<string, unknown>[]) => value is S, thisArg?: any): S | undefined; (predicate: (value: Record<...>, index: number, obj: Record<...>[]) => unknown, thisArg?: any): Record<...> | undefined; } | { ......' has signatures, but none of those signatures are compatible with each other.
我不明白为什么。有没有办法让这个函数同时接收模型类型和对象数组类型?
非常感谢。
解决方案
推荐阅读
- javascript - TypeError:无法读取反应中未定义的属性'0'
- javascript - 如何检查 div .has() 2 是否在 div 中处于同一级别的元素
- javascript - 在“Connect(Items)”的上下文中找不到“store”。要么将根组件包装在
在 react.js 中? - apache - 调用 DataSnap Apache 模块失败
- python - 仅在中间检测物体
- python - 安装 Tensorflow 时出错 - 找不到 numpy 的 RECORD 文件
- entity-framework - 过滤器在我的 ASP.NET Core 存储库中不起作用
- windows - 如何检测从哪里调用协议
- amazon-web-services - 带有非常简单 SSL 插件的官方 Lightsail SSL 对 Debian 实例来说是错误的
- java - 如何避免访问二维数组中的无效位置?