Json-server: Is there any way to injected custom code? (hooks)

Created on 25 Apr 2016  路  3Comments  路  Source: typicode/json-server

Thanks for this great library.

Is there a way to hook in custom code?

For example if I want to be notified after HTTP POST?

Or if I wanted to validate and potentially reject a HTTP PUT?

Most helpful comment

These (server.method and router.render) should be documented somewhere in the module section, very very helpful!! Thanks

All 3 comments

Hi @ashleydavis,

You're welcome.

Sure, simply use the project as a module.
https://github.com/typicode/json-server#module

You can add custom middlewares before the router for validation. And if you need to modify or access, the response before it's sent back, overwrite router.render.

Actually, since JSON Server is built on Express, you can use all the techniques that you would use with Express.

var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()

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

server.put('/:resource/:id', function (req, res, next) {
  if (validate(req)) {
    next()
  } else {
    res.sendStatus(400)
  }
})

router.render = function (req, res) {
  if (req.method === 'POST') console.log('there was a POST')
  res.jsonp(res.locals.data)
} 

server.use(router)
server.listen(3000, function () {
  console.log('JSON Server is running')
})

Great, thanks for your help!

These (server.method and router.render) should be documented somewhere in the module section, very very helpful!! Thanks

Was this page helpful?
0 / 5 - 0 ratings