我有實用程式 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) => {
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) => {
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,
有人有單獨檔案的技巧嗎?傳遞值作為鍵?動態密鑰命名。
uj5u.com熱心網友回復:
您可以向 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");
uj5u.com熱心網友回復:
您可以將資源名稱傳遞給您的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);
希望這能回答你的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324663.html
標籤:javascript 节点.js
