I have a json-server
with the following files:
db.json
:
var faker = require('faker');
module.exports = function () {
var data = {
slack_users_list: slack_users_list(),
slack_users_info: slack_users_info()
}
return data;
}
function slack_users_list() {
const data = {
members: []
}
for (var i = 0; i < 10; i++) {
data.members.push({
id: "user_id_" + i
})
}
return data;
}
function slack_users_info() {
const data = {
user: []
}
for (var i = 0; i < 10; i++) {
data.user.push({
id: "user_id_" + i,
name: faker.internet.userName(),
team_id: faker.datatype.string(),
profile: {
title: faker.name.title(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
title: faker.name.title(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
skype: faker.internet.userName(),
},
})
}
return data;
}
And server.js
:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
// Wrap response depending on the object being called.
router.render = (req, res) => {
if (req.url.startsWith('/slack_users_list')) {
res.jsonp(res.locals.data)
} else if (req.url.startsWith('/slack_users_info')) {
param_user = req.query.user
if (param_user == null) {
res.jsonp({
"ok": false,
"error": "user_not_found"
})
return
}
user_list = res.locals.data.user
user_info = {}
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].id == param_user) {
user_info = user_list[i]
}
}
res.jsonp({ user: user_info })
} else {
res.jsonp(res.locals.data)
}
}
server.use(router)
// Run server on indicated port.
server.listen(port = 3000, () => {
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
So when I call http://localhost:3000/slack_users_list
I get:
{
"members": [
{
"id": "user_id_0"
},
{
"id": "user_id_1"
},
{
"id": "user_id_2"
},
{
"id": "user_id_3"
},
{
"id": "user_id_4"
},
{
"id": "user_id_5"
},
{
"id": "user_id_6"
},
{
"id": "user_id_7"
},
{
"id": "user_id_8"
},
{
"id": "user_id_9"
}
]
}
But if I want to apply pagination to it (e.g. http://localhost:3000/slack_users_list?_page=1&_limit=2
), I get all the same objects, I assume because the pagination is getting applied to the first line of objects and not to each of the element inside members that get generated in db.json.
How can I modify this to apply the pagination on the sub-object members
?
Thanks!
from How can I apply pagination to a subobject in json-server?
No comments:
Post a Comment