all files / keystone/lib/middleware/ api.js

9.52% Statements 2/21
0% Branches 0/20
16.67% Functions 1/6
9.52% Lines 2/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                                                                 
/**
 * Adds shortcut methods for JSON API responses:
 *
 *   * `res.apiResponse(data)`
 *   * `res.apiError(key, err, msg, code)`
 *   * `res.apiNotFound(err, msg)`
 *   * `res.apiNotAllowed(err, msg)`
 *
 * ####Example:
 *
 *     app.all('/api*', keystone.middleware.api);
 *
 * @param {app.request} req
 * @param {app.response} res
 * @param {function} next
 * @api public
 */
 
// The exported function returns a closure that retains
// a reference to the keystone instance, so it can be
// passed as middeware to the express app.
 
module.exports = function (keystone) {
	return function initAPI (req, res, next) {
 
		res.apiResponse = function (data) {
			if (req.query.callback) {
				res.jsonp(data);
			} else {
				res.json(data);
			}
		};
 
		res.apiError = function (key, err, msg, code) {
			msg = msg || 'Error';
			key = key || 'unknown error';
			msg += ' (' + key + ')';
			if (keystone.get('logger')) {
				console.log(msg + (err ? ':' : ''));
				if (err) {
					console.log(err);
				}
			}
			res.status(code || 500);
			res.apiResponse({ error: key || 'error', detail: err });
		};
 
		res.apiNotFound = function (err, msg) {
			res.apiError('data not found', err, msg || 'not found', 404);
		};
 
		res.apiNotAllowed = function (err, msg) {
			res.apiError('access not allowed', err, msg || 'not allowed', 403);
		};
 
		next();
	};
};