Javascript 获取分页续集的下一个偏移量
我想知道分页的正确方法,特别是获取下一页并在响应中让用户知道。我也不想在响应中透露Javascript 获取分页续集的下一个偏移量,javascript,node.js,express,sequelize.js,Javascript,Node.js,Express,Sequelize.js,我想知道分页的正确方法,特别是获取下一页并在响应中让用户知道。我也不想在响应中透露count值 因此,我当前的实现有以下响应: { "offset": 0, "count": 8, "nextPageOffset": 100, "categories": [ { ...... 但是我意识到我的nextPageOffset的值非常错误,可能会产生错误,就像用户可能会跳过一些数据一样 const nextPageOffset
count
值
因此,我当前的实现有以下响应:
{
"offset": 0,
"count": 8,
"nextPageOffset": 100,
"categories": [
{
......
但是我意识到我的nextPageOffset
的值非常错误,可能会产生错误,就像用户可能会跳过一些数据一样
const nextPageOffset = offset + limit
我该怎么做
这是我的控制器:
// Get all the categories.
exports.getCategories = (req, res) => {
const offset = parseInt(req.query.offset, 10)
const limit = parseInt(req.query.limit, 10)
db.Category.findAndCountAll({ where: {}, offset: offset, limit: limit })
.then(data => {
const rows = data.rows
const count = data.count
const object = { }
let nextPageOffset = offset + limit
//if count >
object.offset = offset
object.count = count
object.nextPageOffset = nextPageOffset
object.categories = rows
res.send(object)
})
.catch(err => {
console.log("Error get categories: " + err.message)
res.status(500).send({
message: "An error has occured while retrieving data."
})
})
}
我的方法是,在使用分页的任何路由响应中,使所有调用都相同,因为这样我的项目最终看起来像这样 在你的例子中,我会写:
const listAllProducts=async(req,res)=>{
const page=util.parser.tryParseInt(req.query.page,0);
const limit=util.parser.tryParseInt(req.query.limit,10);
试一试{
const result=wait db.products.findAndCountAll({
其中:{
活动:“1”,
},
偏移量:限制*页,
极限:极限,
订单:[“id”,“ASC”],
});
res.json(util.response.paging(结果、页面、限制));
}捕捉(错误){
res.json({error:err.message});
}
};
为了保持一致,我会让我的回答看起来像
exports.paging = (sequelizeResult, page, limit) => ({
page: page,
limit: limit,
total: sequelizeResult.count,
data: sequelizeResult.rows,
})
这样,您就不会像当前那样在数据
前面加上类别
,如果是用户
或产品
等,那么“模式”就会改变
注意:遇到结果
而不是数据
路线会像这样工作
GET /products
or
GET /products?limit=2&page=2
对于GET/products?limit=2&page=2
HTTP/1.1 200 OK
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Type: application/json; charset=utf-8
Content-Length: 237
ETag: W/"ed-gK+xNNQgqp7jq/ZbZ3qja3u0680"
Date: Thu, 14 May 2020 09:36:55 GMT
Connection: close
{
"page": 2,
"limit": 2,
"total": 9,
"data": [
{
"id": 5,
"name": "Product 5",
"description": "Description for product 5",
"price": "1.25",
"active": true
},
{
"id": 6,
"name": "Product 6",
"description": "Description for product 6",
"price": "6.55",
"active": true
}
]
}
由于这一点,我没有机会说谢谢,这是一个很大的帮助,特别是对于像我这样的新手来说。我真的很喜欢这样的生产准备实践!不客气,StackOverflow社区太棒了