2014-06-05 00:42:18 +00:00
|
|
|
/*!
|
2013-05-24 14:59:59 +00:00
|
|
|
* Module dependencies.
|
|
|
|
*/
|
|
|
|
|
2014-11-12 11:36:16 +00:00
|
|
|
var loopback = require('../../lib/loopback');
|
2014-10-22 21:29:56 +00:00
|
|
|
var async = require('async');
|
2013-05-24 14:59:59 +00:00
|
|
|
|
2014-06-05 00:42:18 +00:00
|
|
|
/*!
|
2013-05-24 14:59:59 +00:00
|
|
|
* Export the middleware.
|
|
|
|
*/
|
|
|
|
|
|
|
|
module.exports = rest;
|
|
|
|
|
|
|
|
/**
|
2014-06-05 00:42:18 +00:00
|
|
|
* Expose models over REST.
|
2014-10-30 20:49:47 +00:00
|
|
|
*
|
2014-06-05 00:42:18 +00:00
|
|
|
* For example:
|
|
|
|
* ```js
|
|
|
|
* app.use(loopback.rest());
|
|
|
|
* ```
|
|
|
|
* For more information, see [Exposing models over a REST API](http://docs.strongloop.com/display/DOC/Exposing+models+over+a+REST+API).
|
|
|
|
* @header loopback.rest()
|
2013-05-24 14:59:59 +00:00
|
|
|
*/
|
|
|
|
|
2014-11-04 10:27:49 +00:00
|
|
|
function rest() {
|
2014-10-22 21:29:56 +00:00
|
|
|
return function restApiHandler(req, res, next) {
|
2013-07-17 21:29:43 +00:00
|
|
|
var app = req.app;
|
2014-11-04 10:27:49 +00:00
|
|
|
var restHandler = app.handler('rest');
|
2014-02-04 15:17:32 +00:00
|
|
|
|
2014-10-30 20:49:47 +00:00
|
|
|
if (req.url === '/routes') {
|
2014-11-04 10:27:49 +00:00
|
|
|
return res.send(restHandler.adapter.allRoutes());
|
2014-10-30 20:49:47 +00:00
|
|
|
} else if (req.url === '/models') {
|
2014-02-19 23:14:31 +00:00
|
|
|
return res.send(app.remotes().toJSON());
|
2014-10-22 21:29:56 +00:00
|
|
|
}
|
|
|
|
|
2014-11-04 10:27:49 +00:00
|
|
|
var preHandlers;
|
|
|
|
|
|
|
|
if (!preHandlers) {
|
|
|
|
preHandlers = [];
|
|
|
|
var remotingOptions = app.get('remoting') || {};
|
|
|
|
|
|
|
|
var contextOptions = remotingOptions.context;
|
|
|
|
if (contextOptions !== false) {
|
|
|
|
if (typeof contextOptions !== 'object')
|
|
|
|
contextOptions = {};
|
|
|
|
preHandlers.push(loopback.context(contextOptions));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (app.isAuthEnabled) {
|
2014-02-04 15:17:32 +00:00
|
|
|
// NOTE(bajtos) It would be better to search app.models for a model
|
|
|
|
// of type AccessToken instead of searching all loopback models.
|
|
|
|
// Unfortunately that's not supported now.
|
|
|
|
// Related discussions:
|
|
|
|
// https://github.com/strongloop/loopback/pull/167
|
|
|
|
// https://github.com/strongloop/loopback/commit/f07446a
|
|
|
|
var AccessToken = loopback.getModelByType(loopback.AccessToken);
|
2014-11-04 10:27:49 +00:00
|
|
|
preHandlers.push(loopback.token({ model: AccessToken }));
|
2014-02-04 15:17:32 +00:00
|
|
|
}
|
2013-05-24 14:59:59 +00:00
|
|
|
}
|
2014-11-04 10:27:49 +00:00
|
|
|
|
|
|
|
async.eachSeries(preHandlers.concat(restHandler), function(handler, done) {
|
2014-10-22 21:29:56 +00:00
|
|
|
handler(req, res, done);
|
|
|
|
}, next);
|
2014-02-04 15:17:32 +00:00
|
|
|
};
|
2013-05-24 14:59:59 +00:00
|
|
|
}
|