feat: complete day 2

This commit is contained in:
Ayobami
2025-07-11 18:05:50 +01:00
parent b277c8182d
commit 325788cb39
8 changed files with 456 additions and 5 deletions
+82
View File
@@ -0,0 +1,82 @@
const { Op } = require("sequelize");
class PaginationService {
/**
* Handle offset-based pagination with sorting
*/
static async paginateWithSort(model, options = {}) {
const {
page = 1,
limit = 10,
sort = "id",
direction = "ASC",
where = {},
} = options;
const offset = (page - 1) * limit;
const order = [[sort, direction.toUpperCase()]];
const { count, rows } = await model.findAndCountAll({
where,
order,
limit: parseInt(limit),
offset: parseInt(offset),
});
const totalPages = Math.ceil(count / limit);
return {
total: count,
page: parseInt(page),
totalPages,
list: rows,
};
}
/**
* Handle cursor-based pagination
*/
static async paginateWithCursor(model, options = {}) {
const {
id,
limit = 10,
sort = "id",
direction = "ASC",
where = {},
} = options;
const order = [[sort, direction.toUpperCase()]];
const cursorWhere = {
...where,
[sort]: {
[direction.toUpperCase() === "ASC" ? Op.gt : Op.lt]: id,
},
};
const rows = await model.findAll({
where: cursorWhere,
order,
limit: parseInt(limit),
});
return {
id: parseInt(id),
list: rows,
};
}
/**
* Get odd order IDs
*/
static async getOddOrders(model) {
return await model.findAll({
where: {
id: {
[Op.mod]: [2, 1], // id % 2 = 1 (odd numbers)
},
},
});
}
}
module.exports = PaginationService;