今日已更新 35 条资讯 | 累计 37284 条内容
关于我们

The Criteria pattern in NestJS: what a client may ask for is a file, not a signature

Hector Angel Gomez Robaina 2026年08月21日 11:10 1 次阅读 来源:Dev.to

The Criteria pattern in NestJS One single way to filter, sort and paginate any list. Five parameters and a find() The example running through this article is a library catalogue. A book stores this: // src/book/book.schema.ts @ Schema ({ timestamps : true }) export class Book { @ Prop () title : string ; @ Prop ({ type : Types . ObjectId , ref : " Author " }) author : Types . ObjectId ; @ Prop () publishedAt : Date ; @ Prop () copies : number ; // copies on the shelf @ Prop () available : boolean ; @ Prop () acquisitionPrice : number ; // what it cost us: internal, never published } The author's name is not here: it lives in the authors collection, on the other side of that reference. And the screen consuming the catalogue is a table with a search box, per-column filters and pagination. The endpoint feeding it is written once and grows by accretion. It starts returning a page with a fixed order, and by the time the table has all its filters it has become this: // src/book/book.controller.ts @ Controller ( " books " ) export class BookController { constructor ( @ InjectModel ( Book . name ) private readonly model : Model < BookDocument > , ) {} @ Get () async getAll ( @ Query ( " title " ) title ?: string , @ Query ( " available " ) available ?: string , @ Query ( " minCopies " ) minCopies ?: string , @ Query ( " sortBy " ) sortBy ?: string , @ Query ( " page " ) page ?: string , ) { const filter : FilterQuery < BookDocument > = {}; if ( title ) { filter . title = { $regex : title , $options : " i " }; } if ( available ) { filter . available = available === " true " ; } if ( minCopies ) { filter . copies = { $gte : Number ( minCopies ) }; } const current = Number ( page ?? 1 ); const [ items , total ] = await Promise . all ([ this . model . find ( filter ) . sort ({ [ sortBy ?? " createdAt " ]: - 1 }) . skip (( current - 1 ) * 20 ) . limit ( 20 ), this . model . countDocuments ( filter ), ]); return { items : items , total : total , page : current }; } } There are co

本文内容来源于互联网,版权归原作者所有
查看原文