json-server icon indicating copy to clipboard operation
json-server copied to clipboard

Modify the lowdb database directly?

Open HomenSimpsor opened this issue 10 years ago • 3 comments

Let's say you POST /transactions with { amount: 100, from: "jim" } but you want the server to add a timestamp so that a GET /transactions/1 would return { amount: 100, from: "jim", created: 1461260299 }.

Is it doable with json-server to add custom behavior to a particular route? Or is json-server always expecting the client to provide the full record to be stored except the id?

HomenSimpsor avatar Apr 21 '16 17:04 HomenSimpsor

Sure, I'd say you don't even need to access lowdb. Simply add a middleware on POST /transaction and add to the request body a timestamp.

var jsonServer = require('json-server')

// Returns an Express server
var server = jsonServer.create()

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

// Add custom routes
server.post('/transaction', function (req, res, next) {
  res.body.created = Date.now()
  next()
})

// For a "global" middleware
server.use(function (req, res, next) {
  if (req.method === 'POST') {
    req.body.created = Date.now()
  }
  next()
})

// Returns an Express router
var router = jsonServer.router('db.json')
server.use(router)

server.listen(3000)

typicode avatar Apr 21 '16 18:04 typicode

BTW I've added this example in the README.

typicode avatar Apr 21 '16 18:04 typicode

Thanks!

HomenSimpsor avatar Apr 21 '16 20:04 HomenSimpsor