This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/assets/utils/getPagesHelper.js

39 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../utils/errorHandling')
const { serverError } = require('../config/errors')
const helperQueryNumber = require('../utils/helperQueryNumber')
const DEFAULT_OPTIONS = {
2020-08-03 12:04:07 +02:00
order: [['createdAt', 'DESC']]
}
/**
* @description Permet de faire un système de pagination sur un model Sequelize
* @param {Object} Object { req, res, next }
* @param {*} Model Model Sequelize
* @param {Object} options Options avec clause where etc.
*/
2020-08-03 14:14:45 +02:00
async function getPagesHelper (
{ req, res, next },
Model,
options = DEFAULT_OPTIONS
) {
2020-08-03 12:04:07 +02:00
const page = helperQueryNumber(req.query.page, 1)
const limit = helperQueryNumber(req.query.limit, 10)
const offset = (page - 1) * limit
try {
const result = await Model.findAndCountAll({
limit,
offset,
...options
})
const { count, rows } = result
2020-08-03 14:14:45 +02:00
const hasMore = page * limit < count
2020-08-03 12:04:07 +02:00
return res.status(200).json({ totalItems: count, hasMore, rows })
} catch (error) {
console.log(error)
return errorHandling(next, serverError)
}
}
2020-08-03 12:04:07 +02:00
module.exports = getPagesHelper