i have utils pagination.js
exports.getPagination = function (page, size) {
const limit = size ? size : 3;
const offset = page ? page * limit : 0;
return { limit, offset };
};
exports.getPagingData = function (datas, page, limit) {
const { count: total_items, rows: scores } = datas;
const current_page = page ? page : 0;
const total_pages = Math.ceil(total_items / limit);
return { total_items, scores, total_pages, current_page }; // here problem
};
i have use like these
const { page, size, title } = req.query;
const { limit, offset } = pagination.getPagination(page, size);
....
....
.then( async (scores) => {
const resData = pagination.getPagingData(scores, page, limit);
// const resData = pagination.getPagingData(scores, page, limit);
response.ok(res, "load scores data", resData);
my json return
{
"success": true,
"message": "load scores data",
"data": {
"total_items": 4222,
"scores": [
{
"id": 3,
how i can naming flexible scores
when i use the utils on other controller ?
for example
.then( async (events) => {
const resData = pagination.getPagingData(events, page, limit);
response.ok(res, "load events data", resData);
so my json return expected :
{
"success": true,
"message": "load events data",
"data": {
"total_items": 4222,
"events": [
{
"id": 3,
Actual results:
{
"success": true,
"message": "load events data",
"data": {
"total_items": 4222,
"scores": [ // here problem
{
"id": 3,
anyone have trick with separate file ? passing value as key ? dynamic key naming.
CodePudding user response:
You could add another argument to your getPagingData function like so:
exports.getPagingData = function (datas, page, limit, dynamicKey) {
const { count: total_items, rows: scores } = datas;
const current_page = page ? page : 0;
const total_pages = Math.ceil(total_items / limit);
return { total_items, [dynamicKey]: scores, total_pages, current_page }; // here problem
};
then you can call this function
const resData = pagination.getPagingData(events, page, limit, "events");
CodePudding user response:
Something you can do it to pass the resource name to your getPagingData
function. Like so:
exports.getPagingData = function (datas, page, limit, resourceName) {
const { count: total_items, rows } = datas;
const current_page = page ? page : 0;
const total_pages = Math.ceil(total_items / limit);
const result = { total_items, total_pages, current_page };
/**
* DO YOUR PAGINATION LOGIC SOMEWHERE HERE
*/
result[resourceName] = rows;
return result;
};
And when you need to call the function, you call it as shown below:
const resource_name = "events"; // or "scores", as the case may be.
const resData = pagination.getPagingData(scores, page, limit, resource_name);
Hope this answers your question.