# all files / keystone/lib/ updateHandler.js

50% Statements 65/130
32.79% Branches 40/122
50% Functions 8/16
50.78% Lines 65/128

    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
    3071×
    1×
    1×
    1×
    1×

    1×

    7×

    7×
    7×
    7×
    7×
    7×
    7×

    7×
    7×

    7×

    7×
    7×

    1×

    1×

    1×

    7×

    7×
    7×
    7×

    7×

    7×
    7×

    7×
    7×
    7×

    7×
    7×
    7×
    7×

    7×

    7×
    27×
    27×

    7×
    7×
    7×

    7×
    7×

    7×

    7×

    7×

    7×

    7×

    7×
    7×

    7×

    7×

    27×

    27×
    27×

    27×

    27×

    27×

    27×

    27×

    27×

    27×

    7×

    1×
     var _ = require('lodash');
    var keystone = require('../');
    var async = require('async');
    var evalDependsOn = require('../fields/utils/evalDependsOn.js');
    var debug = require('debug')('keystone:lib:updateHandler');
    /**
     * UpdateHandler Class
     *
     * @param {Object} item to update
     * @api public
     */

    function UpdateHandler (list, item, req, res, options) {

    	Iif (!(this instanceof UpdateHandler)) {
    		return new UpdateHandler(list, item);
    	}

    	this.list = list;
    	this.item = item;
    	this.req = req;
    	this.res = res;
    	this.user = req.user;
    	this.options = options || {};

    	Eif (!this.options.errorMessage) {
    		this.options.errorMessage = 'There was a problem saving your changes:';
    	}

    	Iif (this.options.user) {
    		this.user = this.options.user;
    	}

    	this.validationMethods = {};
    	this.validationErrors = {};

    }

    /**
     * Adds a custom validation method for a given path
     *
     * @param {string} path to call method for
     * @param {function} method to call
     * @api public
     */

    UpdateHandler.prototype.validate = function (path, fn) {
    	this.validationMethods[path] = fn;
    	return this;
    };

    /**
     * Adds a validationError to the updateHandler; can be used before
     * `.process()` is called to handle errors generated by custom pre-
     * processing.
     *
     * @param {string} path that failed validation
     * @param {string} message to display
     * @param {string} error type (defaults to 'required')
     * @api public
     */

    UpdateHandler.prototype.addValidationError = function (path, msg, type) {
    	this.validationErrors[path] = {
    		name: 'ValidatorError',
    		path: path,
    		message: msg,
    		type: type || 'required',
    	};
    	return this;
    };

    /**
     * Processes data from req.body, req.query, or any data source.
     *
     * Options:
     * - fields (comma-delimited list or array of field paths)
     * - flashErrors (boolean, default false; whether to push validation errors to req.flash)
     * - ignoreNoedit (boolean, default false; whether to ignore noedit settings on fields)
     * - validationErrors (object; validation errors from previous form handling that should be included)
     *
     * @param {Object} data
     * @param {Object} options (can be comma-delimited list of fields) (optional)
     * @param {Function} callback (optional)
     * @api public
     */

    UpdateHandler.prototype.process = function (data, options, callback) {

    	var usingDefaultFields = false;

    	Eif (typeof options === 'function') {
    		callback = options;
    		options = null;
    	}

    	Iif (typeof callback !== 'function') {
    		callback = function () {};
    	}

    	// Initialise options

    	Eif (!options) {
    		options = {};
    	} else if (typeof options === 'string') {
    		options = { fields: options };
    	}

    	Eif (!options.fields) {
    		options.fields = _.keys(this.list.fields);
    		usingDefaultFields = true;
    	} else if (typeof options.fields === 'string') {
    		options.fields = options.fields.split(',').map(function (i) { return i.trim(); });
    	}

    	options.required = options.required || {};
    	options.errorMessage = options.errorMessage || this.options.errorMessage;
    	options.invalidMessages = options.invalidMessages || {};
    	options.requiredMessages = options.requiredMessages || {};

    	// Parse a string of required fields into field paths
    	Iif (typeof options.required === 'string') {
    		var requiredFields = options.required.split(',').map(function (i) { return i.trim(); });
    		options.required = {};
    		requiredFields.forEach(function (path) {
    			options.required[path] = true;
    		});
    	}

    	// Make sure fields with the required option set are included in the required paths
    	options.fields.forEach(function (path) {
    		var field = (path instanceof keystone.Field) ? path : this.list.field(path);
    		Iif (field && field.required) {
    			options.required[field.path] = true;
    		}
    	}, this);

    	// TODO: The whole progress queue management code could be a lot neater...
    	var actionQueue = [];
    	var addValidationError = this.addValidationError.bind(this);
    	var validationErrors = this.validationErrors;

    	var progress = function (err) {
    		Iif (err) {
    			if (options.logErrors) {
    				console.log('Error saving changes to ' + this.item.list.singular + ' ' + this.item.id + ':');
    				console.log(err);
    			}
    			callback(err, this.item, this);
    		} else Iif (_.size(validationErrors)) {
    			if (options.flashErrors) {
    				this.req.flash('error', {
    					type: 'ValidationError',
    					title: options.errorMessage,
    					list: _.map(validationErrors, 'message'),
    				});
    			}
    			callback({
    				message: 'Validation failed',
    				name: 'ValidationError',
    				errors: validationErrors,
    			}, this.item, this);
    		} else Iif (actionQueue.length) {
    			// TODO: parallel queue handling for cloudinary uploads?
    			actionQueue.pop()();
    		} else {
    			saveItem();
    		}
    	}.bind(this);

    	var saveItem = function () {

    		// Make current user available to pre/post save events
    		this.item._req_user = this.user;

    		this.item.save(function (err) {
    			Iif (err) {
    				if (err.name === 'ValidationError') {
    					// don't log simple validation errors
    					if (options.flashErrors) {
    						this.req.flash('error', {
    							type: 'ValidationError',
    							title: options.errorMessage,
    							list: _.map(err.errors, 'message'),
    						});
    					}
    				} else {
    					if (options.logErrors) {
    						console.log('Error saving changes to ' + this.item.list.singular + ' ' + this.item.id + ':');
    						console.log(err);
    					}
    					if (options.flashErrors) {
    						this.req.flash('error', 'There was an error saving your changes: ' + err.message + ' (' + err.name + (err.type ? ': ' + err.type : '') + ')');
    					}
    				}
    			}
    			return callback(err, this.item, this);
    		}.bind(this));
    	}.bind(this);

    	async.forEach(options.fields, function (path, callback) {

    		// console.log('Processing field ' + path);
    		var message;

    		var field = (path instanceof keystone.Field) ? path : this.list.field(path);
    		var invalidated = false;

    		Iif (!field) {
    			throw new Error('UpdateHandler.process called with invalid field path: ' + path);
    		}

    		// skip uneditable fields
    		Iif (usingDefaultFields && field.noedit && !options.ignoreNoedit) {
    			// console.log('Skipping field ' + path + ' (noedit: true)');
    			return callback();
    		}

    		// Some field types have custom behaviours for queueing or validation
    		switch (field.type) {

    			case 'localfile':
    			case 'localfiles':
    			case 'cloudinaryimage':
    			case 'cloudinaryimages':
    			case 'azurefile':
    			case 's3file':
    				actionQueue.push(field.getRequestHandler(this.item, this.req, options.paths, function (err) {
    					if (err && options.flashErrors) {
    						this.req.flash('error', field.label + ' upload failed - ' + err.message);
    					}
    					progress(err);
    				}.bind(this)));
    				break;

    			case 'location':
    				actionQueue.push(field.getRequestHandler(this.item, this.req, options.paths, function (err) {
    					if (err && options.flashErrors) {
    						this.req.flash('error', field.label + ' improve failed - ' + (err.status_text || err.status));
    					}
    					progress(err);
    				}.bind(this)));
    				break;

    			case 'password':
    				// passwords should only be set if a value is provided.
    				// if no value is provided, as long as the field isn't required or empty, bail.
    				if (!data[field.path] && (!options.required[field.path] || this.item.get(field.path))) {
    					return callback();
    				}
    				// validate the password fields match, with a custom error message.
    				if (data[field.path] !== data[field.paths.confirm]) {
    					message = options.invalidMessages[field.path + '_match'] || 'Passwords must match';
    					addValidationError(field.path, message);
    					invalidated = true;
    				}
    				break;

    		}

    		// validate field input, unless it's already been invalidated by field-specific behaviour
    		Iif (!invalidated && !field.inputIsValid(data)) {
    			// console.log('Field ' + field.path + ' is invalid');
    			message = options.invalidMessages[field.path] || field.options.invalidMessage || 'Please enter a valid ' + field.typeDescription + ' in the ' + field.label + ' field';
    			addValidationError(field.path, message);
    			invalidated = true;
    		}

    		// validate required fields, unless they've already been invalidated by field-specific behaviour
    		Iif (!invalidated && options.required[field.path] && !field.inputIsValid(data, true, this.item) && !validationErrors[field.path]) {
    			// console.log('Field ' + field.path + ' is required, but not provided.');
    			if (!field.dependsOn || evalDependsOn(field.dependsOn, data)) {
    				debug('validate dependsOn required', field.dependsOn);
    				// field is required only if dependsOn is true
    				message = options.requiredMessages[field.path] || field.options.requiredMessage || field.label + ' is required';
    				addValidationError(field.path, message);
    				invalidated = true;
    			}

    		}

    		// check for a custom validation rule at the path, and run it (unless the field is already invalid)
    		Iif (!invalidated && this.validationMethods[field.path]) {
    			message = this.validationMethods[field.path](data);
    			if (message) {
    				addValidationError(field.path, message);
    			}
    			invalidated = true;
    		}

    		field.updateItem(this.item, data, callback);

    	}.bind(this), function () {
    		progress();
    	});
    };

    /*!
     * Export class
     */

    module.exports = UpdateHandler;