寻求指导:基于PostgreSQL与Drizzle ORM构建多功能API查询类
从Mongoose迁移到Drizzle ORM:实现链式API查询类
背景
之前使用Mongoose搭配MongoDB时,我创建了一个支持链式调用的APIFeatures类,让API可以高效实现过滤、排序、字段选择、分页等功能。
示例请求
url/api/employee?sort=name&select=id,name,email&page=2&limit=10
参数说明
sort:按姓名升序排序select:仅返回响应中的id、name和email字段page:指定页码limit:设置每页结果数量
Mongoose中的使用方式
// 构建查询 const features = new APIFeatures( Employee.find(), req.query ) .sort() .select() .paginate(); // 执行查询 const employees = await features.query;
原APIFeatures类实现
class APIFeatures { constructor(query, queryString) { this.query = query; this.queryString = queryString; } sort() { if (this.queryString.sort) { const sortBy = this.queryString.sort.split(",").join(" "); this.query = this.query.sort(sortBy); } else { this.query = this.query.sort("name"); } return this; } select() { if (this.queryString.fields) { const fields = this.queryString.select.split(",").join(" "); this.query = this.query.select(fields); } else { this.query = this.query.select("-__v"); } return this; } paginate() { const page = this.queryString.page * 1 || 1; const limit = this.queryString.limit * 1 || 10; const skip = (page - 1) * limit; this.query = this.query.skip(skip).limit(limit); return this; } } module.exports = APIFeatures;
当前需求
现在我已切换到PostgreSQL并使用Drizzle ORM,希望创建一个具备相同功能的链式调用类,但遇到了困难,寻求帮助。
内容的提问来源于stack exchange,提问作者sachin nishad
相关产品推荐
相关产品推荐

