возвращает имя json пользовательские утилиты nodejs

#javascript #node.js

Вопрос:

у меня есть 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  };  

у меня есть такое применение

 const { page, size, title } = req.query;  const { limit, offset } = pagination.getPagination(page, size); .... ....  .then( async (scores) =gt; {  const resData = pagination.getPagingData(scores, page, limit);  // const resData = pagination.getPagingData(scores, page, limit);  response.ok(res, "load scores data", resData);  

мое возвращение json

 {  "success": true,  "message": "load scores data",  "data": {  "total_items": 4222,  "scores": [  {  "id": 3,  

как я могу быть гибким scores , когда я использую utils на другом контроллере ?

например

 .then( async (events) =gt; {  const resData = pagination.getPagingData(events, page, limit);  response.ok(res, "load events data", resData);  

так что мое возвращение json ожидается :

 {  "success": true,  "message": "load events data",  "data": {  "total_items": 4222,  "events": [  {  "id": 3,   

Фактические результаты:

 {  "success": true,  "message": "load events data",  "data": {  "total_items": 4222,  "scores": [ // here problem  {  "id": 3,  

у кого-нибудь есть трюк с отдельным файлом ? передача значения в качестве ключа ? динамическое именование ключей.

Ответ №1:

Вы можете добавить еще один аргумент в свою функцию getPagingData, например:

 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  };  

затем вы можете вызвать эту функцию

 const resData = pagination.getPagingData(events, page, limit, "events");  

Ответ №2:

Что-то, что вы можете сделать, чтобы передать имя ресурса вашей getPagingData функции. Вот так:

 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; };  

И когда вам нужно вызвать функцию, вы вызываете ее, как показано ниже:

 const resource_name = "events"; // or "scores", as the case may be. const resData = pagination.getPagingData(scores, page, limit, resource_name);  

Надеюсь, это ответ на ваш вопрос.