/**
 * lib/RestAPI.js
 *
 * The main file for the API manager.
 */

var Route = require('./route'),
	logger = require('./logger'),
	responder = require('./responder'),
	bodyParser = require('body-parser'),
	q = require('q');

/**
 * Constructor. Takes in an Express app.
 */
function RestAPI(expressApp) {
	this.expressApp = expressApp;

	// add middleware
	this.expressApp.use(bodyParser.json({
		strict: true
	}));
	this.expressApp.use(responder);
}

/**
 * Route function. Returns a Route object with the given path, attached to this
 * RestAPI instance.
 *
 * @param {string} path The desired path for the route, eg '/user'.
 */
RestAPI.prototype.route = function(path) {
	return new Route(this, path);
};

/**
 * Param function. Adds a URL param handler to express using the given
 * function.
 *
 * @param {string} paramString The string to check the request path against, eg
 *	 "userId".
 *
 * @param {string} resultName The key to store the param result under in the url
 *   params object that gets passed to service functions, eg "user".
 *
 * @param {function} handler The handler function for the parameter. Should
 *   return a promise that resolves with (result, status).
 *
 * @return {object} this For chaining.
 */
RestAPI.prototype.param = function(paramString, resultName, handler) {
	this.expressApp.param(paramString, function(req, res, next, paramValue) {
		q.fcall(handler, paramValue)
		.then(function(result, status) {
			status = status || 200;

			if (status === 200) {
				req.urlParams[resultName] = result;

				next();
			} else {
				return res.respond({
					status: status,
					content: result
				});
			}
		})
		.catch(function(err) {
			logger.error(err);

			res.respond(500);
		});
	});
};

module.exports = RestAPI;

@@ -1441,16 +1441,20 @@
 s) %7B%0A%09%09%09
+var 
 status =
@@ -1458,22 +1458,521 @@
 s = 
-status %7C%7C 200;
+200,%0A%09%09%09%09content = %5B%5D,%0A%09%09%09%09error = %7B%7D,%0A%09%09%09%09message = '';%0A%0A%09%09%09if (typeof result === 'number') %7B%0A%09%09%09%09// allow the client to pass back an explicit status code%0A%09%09%09%09status = result;%0A%09%09%09%7D else if (typeof result === 'object') %7B%0A%09%09%09%09// allow the client to explicitly construct a response by passing in%0A%09%09%09%09// _status, _content, _error, or _message parameters%0A%09%09%09%09status = result._status %7C%7C status;%0A%09%09%09%09content = result._content %7C%7C result;%0A%09%09%09%09error = result._error %7C%7C error;%0A%09%09%09%09message = result._message %7C%7C message;%0A%09%09%09%7D
 %0A%0A%09%09
@@ -2119,22 +2119,65 @@
 ontent: 
-result
+content,%0A%09%09%09%09%09error: error,%0A%09%09%09%09%09message: message
 %0A%09%09%09%09%7D);

Allow param handlers to return status codes.