DEV Community

Aboucodeur
Aboucodeur

Posted on

Pern Stack pagination middleware


module.exports = (table, _max_limits) => {
    // global variable
    let queryString = `select * from ${table}`
    let arr = []
    let results = {}

    find(queryString)
        .then((data) => arr = data)
        .catch(err => res.status(400).json({ err }))


    return (req, res, next) => {
        // like convention
        const { page, limit } = req.query

        // user input
        const intPage = parseInt(page, 10) || 1
        const intLimit = parseInt(limit, 10)
        // control user limit
        const intCtrLimit = intLimit > _max_limits ? _max_limits : intLimit // user limit > _max_limits

        // algorithms
        let totals = arr.length
        let numberOfPages = Math.round(((totals) / intCtrLimit))
        let startIndex = (intPage - 1) * intCtrLimit
        let endIndex = ((intPage * intCtrLimit) - 1)

        // output
        let prevPage = (intPage > 0 && intPage <= numberOfPages) ? intPage - 1 : 1
        let nexPage = (intPage < numberOfPages) ? intPage + 1 : numberOfPages // not equals but is add one

        // errors gestion
        if (intPage <= numberOfPages) {
            if (intPage > 0) {
                results = {
                    log: `result of request : page=${intPage} & limit=${intCtrLimit} `,
                    totals,
                    prevPage,
                    nexPage,
                    numberOfPages,
                    limit: intCtrLimit,
                    startIndex,
                    endIndex: endIndex + 1 // like array slice 
                }
            }
        }

        // like user paigination
        let paginateDatas = arr.slice(results?.startIndex, results?.endIndex)
        results.datas = paginateDatas

        // like middleware principe
        req.paginateResults = results
        next()
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)