sleepify
An unobtrusive, easy to use library to quickly prototype relational REST apis in Express.
Install
npm i -S sleepify
Changes (v1.1.0)
- Plugin now accepts an express app or router as a first parameter. This was necessary to drop the express dependency.
//Previous behaviour//let usersRouter = sleepify(userPlugin) //Current behaviourlet usersRouter = express //Equivalentlet usersRouter = //usersRouter points to the same router passed to it
Usage (TL;DR):
let express = let bodyParser = let sleepify sleepymem = let app = app moduleexports = app //Dummy memorystorelet memDB = {}memDBcars = id: '0' name: 'Suzuki' id: '1' name: 'Honda' id: '2' name: 'BMW' id: '3' name: 'MX5'memDBusers = id: '0' name: 'Foo' cars: memDBcars id: '1' name: 'Bar' cars: memDBcars //sleepymem is a basic in-memory pluginlet userPlugin = rel // This router will point to the following endpoints:// GET /users// GET /users/:userId// POST /users// PATCH /users/:userId// DELETE /users/:userId// GET /users/:userId/cars// GET /users/:userId/cars/:carId// PUT /users/:userId/cars/:carIdlet usersRouter = express let apiRouter = expressapiRouterapp
Plugin methods:
plugin.pre(action, middleware) / plugin.post(action, middleware)
:
action
: The action the middleware should be applied to. One of the actions fromACTIONS
.middleware
:function (req, res, next) / Array
- An express middleware or an array of them.
action
can be replaced by middleware
. This is equivalent to plugin.pre(ACTIONS.ALL, middleware)
or plugin.post(ACTIONS.ALL, middleware)
respectively.
plugin.rel(plugin)
:
plugin
: An instance of a plugin to be nested. Much like a nested router.
Plugins
Plugins are a way to define how an action should be performed.
A plugin takes an options
object:
options
:
name
:String
(required) - The prefix for these routes (for example'user'
).plural
:String
(optional, default:name + 's'
) - The prefix for these routes (for example'facilities'
).model
:AnyObject
(optional, default:undefined
) - An object representing the model to be interacted with. This is available later inreq.slp.model
expose
:Array
(optional, default:ACTIONS.ALL
) - The endpoints to expose.methods
:Object
(required, default:noop object
) - An object containing at least one of the actions defined inACTIONS
as a key with a value offunction (req, done)
describing the implementation of this specific method. Callback:done(statusCode / Error, responseObject)
.
Example:
name: 'facility' plural: 'facilities' model: mongoose expose: ACTIONSGET ACTIONSLIST methods: { reqslpmodel } { reqslpmodel }
Extending plugins
An example implementation is available here.
MongoosePlugin
will be available soon in a different repo.
TODO
- Add support for collection delete.
- Allow expose endpoint selection in Plugins.
- Add support for other node-based frameworks (koa, restify...).
Development
Install dependencies: npm i
Run tests: npm test