all files / keystone/lib/ view.js

53.54% Statements 68/127
47.67% Branches 41/86
38.89% Functions 7/18
58.12% Lines 68/117
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374                              13×       13×       13× 13×   13× 13× 13× 13×                           12× 12× 12×   12×                                           12×                                               11×                     10×                                                                                                                 10×                                                                                                                                                                                                                                                               12× 12×   12×                   12×         12× 12×   12×     12×           12× 12×   12× 31×   24×           12×        
/*!
 * Module dependencies.
 */
 
var _ = require('lodash');
var async = require('async');
var keystone = require('../');
var utils = require('keystone-utils');
 
/**
 * View Constructor
 * =================
 *
 * Helper to simplify view logic in a Keystone application
 *
 * @api public
 */
 
function View (req, res) {
 
	Iif (!req || req.constructor.name !== 'IncomingMessage') {
		throw new Error('Keystone.View Error: Express request object is required.');
	}
 
	Iif (!res || res.constructor.name !== 'ServerResponse') {
		throw new Error('Keystone.View Error: Express response object is required.');
	}
 
	this.req = req;
	this.res = res;
 
	this.initQueue = [];	// executed first in series
	this.actionQueue = [];	// executed second in parallel, if optional conditions are met
	this.queryQueue = [];	// executed third in parallel
	this.renderQueue = [];	// executed fourth in parallel
 
}
 
module.exports = View;
 
 
/**
 * Adds a method (or array of methods) to be executed in parallel
 * to the `init`, `action` or `render` queue.
 *
 * @api public
 */
 
View.prototype.on = function (on) {
 
	var req = this.req;
	var callback = arguments[1];
	var values;
 
	Iif (typeof on === 'function') {
 
		/* If the first argument is a function that returns truthy then add the second
		 * argument to the action queue
		 *
		 * Example:
		 *
		 *     view.on(function() {
		 *             var thing = true;
		 *             return thing;
		 *         },
		 *         function(next) {
		 *             console.log('thing is true!');
		 *             next();
		 *         }
		 *     );
		 */
 
		if (on()) {
			this.actionQueue.push(callback);
		}
 
	} else if (utils.isObject(on)) {
 
		/* Do certain actions depending on information in the response object.
		 *
		 * Example:
		 *
		 *     view.on({ 'user.name.first': 'Admin' }, function(next) {
		 *         console.log('Hello Admin!');
		 *         next();
		 *     });
		 */
 
		var check = function (value, path) {
 
			var ctx = req;
			var parts = path.split('.');
 
			for (var i = 0; i < parts.length - 1; i++) {
				Iif (!ctx[parts[i]]) {
					return false;
				}
				ctx = ctx[parts[i]];
			}
 
			path = _.last(parts);
 
			return (value === true && path in ctx) ? true : (ctx[path] === value);
 
		};
 
		Eif (_.every(on, check)) {
			this.actionQueue.push(callback);
		}
 
	} else if (on === 'get' || on === 'post' || on === 'put' || on === 'delete') {
 
		/* Handle HTTP verbs
		 *
		 * Example:
		 *     view.on('get', function(next) {
		 *         console.log('GOT!');
		 *         next();
		 *     });
		 */
 
		if (req.method !== on.toUpperCase()) {
			return;
		}
 
		if (arguments.length === 3) {
 
			/* on a POST and PUT requests search the req.body for a matching value
			 * on every other request search the query.
			 *
			 * Example:
			 *     view.on('post', { action: 'theAction' }, function(next) {
			 *         // respond to the action
			 *         next();
			 *     });
			 *
			 * Example:
			 *     view.on('get', { page: 2 }, function(next) {
			 *         // do something specifically on ?page=2
			 *         next();
			 *     });
			 */
 
			Iif (utils.isString(arguments[1])) {
				values = {};
				values[arguments[1]] = true;
			} else {
				values = arguments[1];
			}
 
			callback = arguments[2];
 
			var ctx = (on === 'post' || on === 'put') ? req.body : req.query;
 
			if (_.every(values || {}, function (value, path) {
				return (value === true && path in ctx) ? true : (ctx[path] === value);
			})) {
				this.actionQueue.push(callback);
			}
 
		} else {
			this.actionQueue.push(callback);
		}
 
	} else Eif (on === 'init') {
 
		/* Init events are always fired in series, before any other actions
		 *
		 * Example:
		 *     view.on('init', function (next) {
		 *         // do something before any actions or queries have run
		 *     });
		 */
 
		this.initQueue.push(callback);
 
	} else if (on === 'render') {
 
		/* Render events are always fired last in parallel, after any other actions
		 *
		 * Example:
		 *     view.on('render', function (next) {
		 *         // do something after init, action and query middleware has run
		 *     });
		 */
 
		this.renderQueue.push(callback);
 
	}
 
	return this;
 
};
 
var QueryCallbacks = function (options) {
	if (utils.isString(options)) {
		options = { then: options };
	} else {
		options = options || {};
	}
	this.callbacks = {};
	if (options.err) this.callbacks.err = options.err;
	if (options.none) this.callbacks.none = options.none;
	if (options.then) this.callbacks.then = options.then;
	return this;
};
 
QueryCallbacks.prototype.has = function (fn) { return (fn in this.callbacks); };
QueryCallbacks.prototype.err = function (fn) { this.callbacks.err = fn; return this; };
QueryCallbacks.prototype.none = function (fn) { this.callbacks.none = fn; return this; };
QueryCallbacks.prototype.then = function (fn) { this.callbacks.then = fn; return this; };
 
 
/**
 * Queues a mongoose query for execution before the view is rendered.
 * The results of the query are set in `locals[key]`.
 *
 * Keys can be nested paths, containing objects will be created as required.
 *
 * The third argument `then` can be a method to call after the query is completed
 * like function(err, results, callback), or a `populatedRelated` definition
 * (string or array).
 *
 * Examples:
 *
 * view.query('books', keystone.list('Book').model.find());
 *
 *     an array of books from the database will be added to locals.books. You can
 *     also nest properties on the locals variable.
 *
 * view.query(
 *     'admin.books',
 *      keystone.list('Book').model.find().where('user', 'Admin')
 * );
 *
 *     locals.admin.books will be the result of the query
 *     views.query().then is always called if it is available
 *
 * view.query('books', keystone.list('Book').model.find())
 *     .then(function (err, results, next) {
 *         if (err) return next(err);
 *         console.log(results);
 *         next();
 *     });
 *
 * @api public
 */
 
View.prototype.query = function (key, query, options) {
 
	var locals = this.res.locals;
	var parts = key.split('.');
	var chain = new QueryCallbacks(options);
 
	key = parts.pop();
 
	for (var i = 0; i < parts.length; i++) {
		if (!locals[parts[i]]) {
			locals[parts[i]] = {};
		}
		locals = locals[parts[i]];
	}
 
	this.queryQueue.push(function (next) {
		query.exec(function (err, results) {
 
			locals[key] = results;
			var callbacks = chain.callbacks;
 
			if (err) {
				if ('err' in callbacks) {
					/* Will pass errors into the err callback
					 *
					 * Example:
					 *     view.query('books', keystone.list('Book'))
					 *         .err(function (err, next) {
					 *             console.log('ERROR: ', err);
					 *             next();
					 *         });
					 */
					return callbacks.err(err, next);
				}
			} else {
				if ((!results || (utils.isArray(results) && !results.length)) && 'none' in callbacks) {
					/* If there are no results view.query().none will be called
					 *
					 * Example:
					 *     view.query('books', keystone.list('Book').model.find())
					 *         .none(function (next) {
					 *             console.log('no results');
					 *             next();
					 *         });
					 */
					return callbacks.none(next);
				} else if ('then' in callbacks) {
					if (utils.isFunction(callbacks.then)) {
						return callbacks.then(err, results, next);
					} else {
						return keystone.populateRelated(results, callbacks.then, next);
					}
				}
			}
 
			return next(err);
 
		});
	});
 
	return chain;
};
 
 
/**
 * Executes the current queue of init and action methods in series, and
 * then executes the render function. If renderFn is a string, it is provided
 * to `res.render`.
 *
 * It is expected that *most* init and action stacks require processing in
 * series.  If there are several init or action methods that should be run in
 * parallel, queue them as an array, e.g. `view.on('init', [first, second])`.
 *
 * @api public
 */
View.prototype.render = function (renderFn, locals, callback) {
 
	var req = this.req;
	var res = this.res;
 
	Iif (typeof renderFn === 'string') {
		var viewPath = renderFn;
		renderFn = function () {
			if (typeof locals === 'function') {
				locals = locals();
			}
			this.res.render(viewPath, locals, callback);
		}.bind(this);
	}
 
	Iif (typeof renderFn !== 'function') {
		throw new Error('Keystone.View.render() renderFn must be a templatePath (string) or a function.');
	}
 
	// Add actions, queries & renderQueue to the end of the initQueue
	this.initQueue.push.apply(this.initQueue, this.actionQueue);
	this.initQueue.push.apply(this.initQueue, this.queryQueue);
 
	var preRenderQueue = [];
 
	// Add Keystone's global pre('render') queue
	keystone.getMiddleware('pre:render').forEach(function (fn) {
		preRenderQueue.push(function (next) {
			fn(req, res, next);
		});
	});
 
	this.initQueue.push(preRenderQueue);
	this.initQueue.push(this.renderQueue);
 
	async.eachSeries(this.initQueue, function (i, next) {
		if (Array.isArray(i)) {
			// process nested arrays in parallel
			async.parallel(i, next);
		} else Eif (typeof i === 'function') {
			// process single methods in series
			i(next);
		} else {
			throw new Error('Keystone.View.render() events must be functions.');
		}
	}, function (err) {
		renderFn(err, req, res);
	});
 
};