npm json-server

Hello guys, currently i am using fake api of npm json-server. How can i create a custom endpoint because in my db.json i have nested object array and i want to have an endpoint to the child array of my db.json because i only have endpoint to the parent object array I'm Noob, correct me if i use wrong term
{
"users": [
{
"id": 1,
"name": "John",
"age": 30,
"posts": [
{
"id": 101,
"title": "First Post",
"content": "This is the content of the first post."
},
{
"id": 102,
"title": "Second Post",
"content": "This is the content of the second post."
}
]
},
{
"id": 2,
"name": "Alice",
"age": 25,
"posts": [
{
"id": 103,
"title": "Another Post",
"content": "This is another post by Alice."
}
]
}
]
}
{
"users": [
{
"id": 1,
"name": "John",
"age": 30,
"posts": [
{
"id": 101,
"title": "First Post",
"content": "This is the content of the first post."
},
{
"id": 102,
"title": "Second Post",
"content": "This is the content of the second post."
}
]
},
{
"id": 2,
"name": "Alice",
"age": 25,
"posts": [
{
"id": 103,
"title": "Another Post",
"content": "This is another post by Alice."
}
]
}
]
}
1 Reply
Satcha Takam
Satcha Takam2mo ago
hello this is an example code of a custom endpoint with json-server
import jsonServer from 'json-server'

const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

const validator = (request, response, next) => {
console.log()

const { content } = request.body

if (request.method === 'POST' && (!content || content.length < 5)) {
return response.status(400).json({
error: 'too short anecdote, must have length 5 or more'
})
} else {
next()
}
}

server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use(validator)
server.use(router)

server.listen(3001, () => {
console.log('JSON Server is running')
})
import jsonServer from 'json-server'

const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

const validator = (request, response, next) => {
console.log()

const { content } = request.body

if (request.method === 'POST' && (!content || content.length < 5)) {
return response.status(400).json({
error: 'too short anecdote, must have length 5 or more'
})
} else {
next()
}
}

server.use(middlewares)
server.use(jsonServer.bodyParser)
server.use(validator)
server.use(router)

server.listen(3001, () => {
console.log('JSON Server is running')
})