分页序列化的偏移量"/>
获取下一个用于分页序列化的偏移量
我想知道进行分页的正确方法,特别是获取下一页,并在响应中让用户知道。我也不想在响应中透露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."
})
})
}
回答如下:我的方法是使所有使用分页的路由响应中的所有呼叫保持相同,因为这样的项目最终看起来像这样
https://github/balexandre/so61791627
在您的示例中,我会写:
const listAllProducts = async (req, res) => {
const page = util.parser.tryParseInt(req.query.page, 0);
const limit = util.parser.tryParseInt(req.query.limit, 10);
try {
const result = await db.products.findAndCountAll({
where: {
active: '1',
},
offset: limit * page,
limit: limit,
order: [["id", "ASC"]],
});
res.json(util.response.paging(result, page, limit));
} catch (err) {
res.json({ error: err.message });
}
};
并且为了保持一致,我会让我的回答看起来像
exports.paging = (sequelizeResult, page, limit) => ({
page: page,
limit: limit,
total: sequelizeResult.count,
data: sequelizeResult.rows,
})
那样,您就不会像现在那样在data
前面加上categories
前缀,如果是users
或products
,则“模式”将发生变化...
NOTE:遇到result
而不是data
]也很常见
路线会像
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
}
]
}
更多推荐
获取下一个用于分页序列化的偏移量
发布评论