Skip to content

Commit

Permalink
Merge pull request #132 from DigiChanges/feat/NSE-135/MBL/mongoose-ag…
Browse files Browse the repository at this point in the history
…gregate-paginator

feat/NSE-135/MBL/mongoose-aggregate-paginator
  • Loading branch information
Murzbul authored May 31, 2023
2 parents 949d8b9 + 9162ded commit 73f8195
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions src/Shared/Infrastructure/Orm/MongooseAggregatePaginator.ts
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;

0 comments on commit 73f8195

Please sign in to comment.