This library provides a set of default Express routes and handlers for use with JSData to enable rapid RESTful API prototyping
npm install should get you all you need: npm install --save jsdatarouter
The JSDataRouter is an ES6 class that takes a JSData resource definition (the same returned by DS.defineResource) and express router object in its constructor and sets up RESTful routes and handlers on the router passed in. If no router is provided it will create a new one using express.Router()
var DS = require('../DataStore'),
JSDataRouter = require('jsdatarouter'),
express = require('express'),
router = new JSDataRouter(DS.store.definitions.todo).router;
module.exports = function (app) {
app.use('/todo', router);
};
calls the JSData create function with req.body
as the argument
sends the resource instance created in the create function and calls end()
calls the JSData destroy function with resourceId
as the argument
sends a blank 200 response
calls next()
sends the found resource instance and calls end()
retrieves all resource instances from the DataStore by calling the JSData findAll function with req.query
and a param object of the form { with: req.with }
allowing you to specify eager-loads
sends the resource instances located in the findAll function and calls end()
calls the JSData update function on the resource instance with the id of resourceId
using req.body
as an argument
sends the resource instance that was updated in the update function and calls end()
Every function on the JSDataRouter class can be re-implemented to add additional functionality. The example below adds server-side validation to a CREATE route before creating the resource instance.
function validateCreateInput(req) {
// ...
}
class TodoRouter extends JsDataRouter {
beforeCreate(req, res, next) {
validateCreateInput(req);
var errors = req.validationErrors();
if(errors) {
res.send('validation errors: ' + util.inspect(errors), 400).end();
return;
}
next();
}
}
Routes that include a resourceId
parameter will automatically retrieve the resource instance that has the specified ID form the DataStore using an express param callback, and make it available via req.resource
. Query parameters and eager-loads (specified on req.with
) along to the JSData find function when looking up the resource instance.
By default all routes are enabled, but an optional options object can be passed into the constructor as a 3rd argument that allows you to disable each action individually. The example below will setup a new router with only the destroy route disabled.
var router = new JSDataRouter(
DS.store.definitions.state,
express.Router(), {
destroy: false
}
);