typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
73.05k stars 7.02k forks source link

Add pagination info to response body #1469

Closed thim81 closed 10 months ago

thim81 commented 10 months ago

Sharing this script here for those who are looking to add pagination info to the API response for GET /resource endpoints

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
const port = 3004

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

function getLinkByRelFromLinkHeader (linkHeader, rel) {
    if (linkHeader) {
        const match = linkHeader.match(new RegExp(`<([^>]+)>; rel="${rel}"`))
        if (match) {
            return match[1]
        }
    }
    return null
}

// Returned resources will be wrapped in a body property
router.render = (req, res) => {
    if (req.method === 'GET' && req.url && !req.route.path.includes(':')) {
        const obj = {}
        const query = req._parsedUrl.search
        const resource =  req.url.replace('/','').replace(query, '')
        const headers = res.getHeaders();

        // Wrap data
        obj[resource] = res.locals.data

        // Add metadata
        if(headers?.link) {
            obj.metadata = {
                first: getLinkByRelFromLinkHeader(headers.link, 'first'),
                prev: getLinkByRelFromLinkHeader(headers.link, 'prev'),
                next: getLinkByRelFromLinkHeader(headers.link, 'next'),
                last: getLinkByRelFromLinkHeader(headers.link, 'last'),
            }
        }
        // Return wrapped response
        res.jsonp(obj)
    } else {
        res.jsonp(res.locals.data)
    }
}

// Use default router
server.use(router)
server.listen(port, () => {
    console.log(`JSON API Server is running on Port ${port}`)
})
typicode commented 10 months ago

Thanks for sharing :+1: v1 will have that by default (currently alpha).

thim81 commented 10 months ago

Thanks @typicode for your time and hard-work to create the excellent JSON-Server. I'm going to the v1 (alpha) a try, I was not aware of it.

typicode commented 10 months ago

I was not aware of it.

Thank you! It's really new, just published some days ago :) and there will be breaking changes so depending on what you do you may or may not want to use it.