json-server
json-server copied to clipboard
Modify the lowdb database directly?
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?
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)
BTW I've added this example in the README.
Thanks!