Skip to content

chore(enhance): pagination feature #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 48 additions & 4 deletions docs/guide/pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,58 @@ const dataPagination = new DataPagination();

app.get('/users', async (req: Request, res: Response) => {
try {
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;
const { page, limit, sort, select, populate } = req.query;
const options = {
page: parseInt(page as string, 10) || 1,
limit: parseInt(limit as string, 10) || 10,
sort: sort ? JSON.parse(sort as string) : { createdAt: -1 },
select: select ? JSON.parse(select as string) : null,
populate: populate ? JSON.parse(populate as string) : null,
};

const result = await dataPagination.paginateResult(User, page, limit);
const result = await dataPagination.paginateResult(User, {}, options);
res.status(200).json(result);
} catch (err) {
res.status(500).json({ message: 'Failed to paginate users', error: err.message });
}
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
```

## Example query to filter users

You can also filter users based on certain criteria. For example, if you want to filter users older than a certain age, you can modify the query as follows:

```typescript
import express, { Request, Response } from 'express';
import { DataPagination } from 'mongodb-atlas-sdk';
import { User } from '../model/userModel';

const app = express();
const dataPagination = new DataPagination();

app.get('/users', async (req: Request, res: Response) => {
try {
const { page, limit, sort, select, populate, age } = req.query;
const options = {
page: parseInt(page as string, 10) || 1,
limit: parseInt(limit as string, 10) || 10,
sort: sort ? JSON.parse(sort as string) : { createdAt: -1 },
select: select ? JSON.parse(select as string) : null,
populate: populate ? JSON.parse(populate as string) : null,
};

// Example query to filter users older than a certain age
const query = age ? { age: { $gt: parseInt(age as string, 10) } } : {};

const result = await dataPagination.paginateResult(User, query, options);
res.status(200).json(result);
} catch (err) {
res.status(500).json({ message: 'Failed to paginate data', error: err.message });
res.status(500).json({ message: 'Failed to paginate users', error: err.message });
}
});

Expand Down
31 changes: 29 additions & 2 deletions src/core/pagination.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
import mongoose from 'mongoose';
import { logger } from '../logger.ts';

interface PaginationOptions {
page: number;
limit: number;
sort?: any;
select?: any;
populate?: any;
}

export class DataPagination {
async paginateResult(model: mongoose.Model<any>, page: number, limit: number, query: any = {}): Promise<any> {
async paginateResult(model: mongoose.Model<any>, query: any = {}, options: PaginationOptions): Promise<any> {
let { page = 1, limit = 10, sort, select, populate } = options;

if (page < 1) {
page = 1;
}

try {
const skip = (page - 1) * limit;
const result = await model.find(query).sort({ createdAt: -1 }).skip(skip).limit(limit).lean().exec();
let queryBuilder = model.find(query).skip(skip).limit(limit).lean();

if (sort) {
queryBuilder.sort(sort);
} else {
queryBuilder = queryBuilder.sort({ createdAt: -1 }); // Default sorting
}

if (select) {
queryBuilder = queryBuilder.select(select);
}

if (populate) {
queryBuilder = queryBuilder.populate(populate);
}

const result = await queryBuilder.exec();
const total = await model.countDocuments(query).exec();

return {
Expand Down