gpt4 book ai didi

javascript - 获取分页的下一个偏移量 Sequelize

转载 作者:行者123 更新时间:2023-12-03 22:25:48 24 4
gpt4 key购买 nike

我想知道分页的正确方法,特别是获取下一页并在响应中让用户知道它。我也不想在响应中透露 count 值。

所以我目前的实现有这样的 react :

{
"offset": 0,
"count": 8,
"nextPageOffset": 100,
"categories": [
{
......

但是我意识到我的 nextPageOffset 值是错误的,并且可能会产生错误,比如用户可能会跳过一些数据。
const nextPageOffset = offset + limit

我该怎么做?

这是我的 Controller :
// 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.com/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 前缀,如果它是例如 usersproducts,“模式”就会改变......

注意 :遇到 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
}
]
}

关于javascript - 获取分页的下一个偏移量 Sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61791627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com