Nodejs使用偏移量分页API调用

问题描述 投票:0回答:1

如果这个问题已被记录,我深表歉意,请向我指出这些资源。

我有一个nodejs应用程序对Untappd进行api调用,并且每个公共API都限制了调用中返回的最大项数,在这种情况下,最大值为50。我想使用Offset(Skip)设置分页,以便可以浏览600多个项目,而不仅仅是50个。

什么有效我目前正在分页工作,以通过这些不同的部分查看前50个项目...

server.js上的API调用

const untappdAPI = { method: 'GET',
url: 'https://api.untappd.com/v4/user/beers/username',
  qs: 
   { access_token: 'abc123'
    ,limit:'50'
     }    
  };

在server.js上具有分页的app.get

app.get('/untappd', function (req, res) {
  try {
    request(untappdAPI, function (error, response, body) {
        if (error) throw new Error(error);
        const untappdBeers = JSON.parse(body);
        const utBeerList = untappdBeers.response.beers.items.map(item => item );
//pagination
const perPage = 5;
let currentPage = 1;
const totalBeerList = utBeerList.length;
const pageCount = Math.ceil(totalBeerList / perPage);

if(req.query.page) {
  currentPage = parseInt(req.query.page, 10);
}
const start = (currentPage - 1) * perPage;
const end = currentPage * perPage;
        res.render('untappd.ejs', {
          utBeerList:utBeerList.slice(start, end),
          perPage: perPage,
          pageCount: pageCount,
          currentPage: currentPage,
        });
    });   
  } catch(e) {
    console.log("Something went wrong", e)
  }
  });

然后这些项目在名为untappd.ejs的页面上呈现,并且此代码提供了工作分页

untappd.ejs上的EJS客户端分页

<div id="pagination">
<% if (pageCount > 1) { %>
    <ul class="pagination">
        <% if (currentPage > 1) { %>
            <li><a href="?page=1">&laquo;</a></li>
        <% } %>
        <% var i = 1;
        if (currentPage > 5) {
            i = +currentPage - 4;
        } %>
        <% if (i !== 1) { %>
            <li><a href="#">...</a></li>
        <% } %>
        <% for (i; i<=pageCount; i++) { %>
            <% if (currentPage == i) { %>
                <li class="active"><span><%= i %> <span class="sr-only">(current)</span></span></li>
            <% } else { %>
                <li><a href="?page=<%= i %>"><%= i %></a></li>
            <% } %>

            <% if (i == (+currentPage + 4)) { %>
                <li><a href="#">...</a></li>
            <% break; } %>
        <% } %>
        <% if (currentPage != pageCount) { %>
            <li><a href="?page=<%= pageCount %>">&raquo;</a></li>
        <% } %>
    </ul>
<% } %>
</div>

同样,上面的代码很好,我可以正常使用分页,每页5个项目,分页10页,但是我限于这50个项目。从我阅读的有关偏移量的内容来看,偏移量似乎可以让我循环浏览整个600多个项目,但是找不到适合此特定情况的文档/帮助。

我如何将'offset'合并到我正在使用的内容中以对600多个项目的完整列表进行分页?

非常感谢您的帮助!

红色

我很抱歉这个问题已经被记录在案,请向我指出这些资源。我有一个nodejs应用程序,它对Untappd和大多数公共API进行了api调用,但仅限于......>

node.js pagination offset
1个回答
0
投票

documentation非常简单(除非您正在尝试其他方法...但是我假设是/v4/search/beer),您所需要做的就是使用API​​提供的offsetlimit,会像:

offset (int, optional) - The numeric offset that you what results to start
limit (int, optional) - The number of results to return, max of 50, default is 25
© www.soinside.com 2019 - 2024. All rights reserved.