-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #132 from DigiChanges/feat/NSE-135/MBL/mongoose-ag…
…gregate-paginator feat/NSE-135/MBL/mongoose-aggregate-paginator
- Loading branch information
Showing
1 changed file
with
71 additions
and
0 deletions.
There are no files selected for viewing
71 changes: 71 additions & 0 deletions
71
src/Shared/Infrastructure/Orm/MongooseAggregatePaginator.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { Aggregate } from 'mongoose'; | ||
import IPaginator from './IPaginator'; | ||
import IPaginatorConfig from './IPaginatorConfig'; | ||
import ICriteria from '../../Presentation/Requests/ICriteria'; | ||
import BasePaginator from './BasePaginator'; | ||
|
||
class MongooseAggregatePaginator extends BasePaginator implements IPaginator | ||
{ | ||
private aggregate: Aggregate<any[]>; | ||
|
||
constructor(aggregate: Aggregate<any[]>, criteria: ICriteria, config: IPaginatorConfig = { metadata: {}, helper: undefined }) | ||
{ | ||
super(criteria, config); | ||
this.aggregate = aggregate; | ||
} | ||
|
||
public async paginate(): Promise<any> | ||
{ | ||
this.addOrderBy(); | ||
this.addPagination(); | ||
|
||
this.setPerPage(this._perPage); | ||
this.setCurrentPage(); | ||
this.setLasPage(); | ||
this.setFrom(); | ||
this.setTo(); | ||
|
||
let data = await this.aggregate.exec(); | ||
this.total = data.length; | ||
this._perPage = data.length; | ||
|
||
if (this.helper) | ||
{ | ||
data = await this.helper(data); | ||
} | ||
|
||
return data; | ||
} | ||
|
||
// TODO: See when multiple sorts | ||
private addOrderBy() | ||
{ | ||
const sorts = this.sort.get(); | ||
const _objectSort = {}; | ||
|
||
sorts.forEach((value: string, key: string) => | ||
{ | ||
let order: any = value.toUpperCase(); | ||
order = (order === 'DESC') ? -1 : 1; | ||
|
||
const obj = { [key]: order }; | ||
Object.assign(_objectSort, obj); | ||
}); | ||
|
||
void this.aggregate.sort(_objectSort); | ||
} | ||
|
||
private addPagination() | ||
{ | ||
const exist = this.pagination.getExist(); | ||
|
||
if (exist) | ||
{ | ||
void this.aggregate | ||
.skip(this.pagination.getOffset()) | ||
.limit(this.pagination.getLimit()); | ||
} | ||
} | ||
} | ||
|
||
export default MongooseAggregatePaginator; |