# all files / keystone/fields/types/relationship/ RelationshipType.js

61.27% Statements 87/142
48.18% Branches 66/137
31.82% Functions 7/22
62.77% Lines 86/137

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

    1×
    12×
    12×
    12×
    12×
    12×
    12×
    12×
    12×

    1×

    1×

    1×

    1×

    1×

    1×
    12×
    12×
    12×

    12×

    12×
    12×

    12×
    1×

    12×

    1×
    7×
    7×
    5×
    1×

    4×

    7×
    3×

    4×
    2×

    2×

    7×

    1×

    1×
    12×
    12×
    12×
    2×

    10×
    4×
    1×

    4×
    4×

    6×
    1×

    6×
    1×

    12×

    1×
    6×
    6×
    6×
    2×

    2×
    1×

    4×

    4×
    3×

    6×

    1×
    10×

    1×
    14×
    10×

    4×

    4×

    4×
    2×
    2×

    2×
    2×

    4×

    1×

    1×

    1×

    1×

    1×
     var _ = require('lodash');
    var FieldType = require('../Type');
    var keystone = require('../../../');
    var util = require('util');
    var utils = require('keystone-utils');

    /**
     * Relationship FieldType Constructor
     * @extends Field
     * @api public
     */
    function relationship (list, path, options) {
    	this.many = (options.many) ? true : false;
    	this.filters = options.filters;
    	this.createInline = (options.createInline) ? true : false;
    	this._defaultSize = 'full';
    	this._nativeType = keystone.mongoose.Schema.Types.ObjectId;
    	this._underscoreMethods = ['format'];
    	this._properties = ['isValid', 'many', 'filters', 'createInline'];
    	relationship.super_.call(this, list, path, options);
    }
    util.inherits(relationship, FieldType);

    /**
     * Get client-side properties to pass to react field.
     */
    relationship.prototype.getProperties = function () {
    	var refList = this.refList;
    	return {
    		refList: {
    			singular: refList.singular,
    			plural: refList.plural,
    			path: refList.path,
    			key: refList.key,
    		},
    	};
    };

    /**
     * Gets id and name for the related item(s) from populated values
     */

    function expandRelatedItemData (item) {
    	if (!item || !item.id) return undefined;
    	return {
    		id: item.id,
    		name: this.refList.getDocumentName(item),
    	};
    }

    function truthy (value) {
    	return value;
    }

    relationship.prototype.getExpandedData = function (item) {
    	var value = item.get(this.path);
    	if (this.many) {
    		if (!value || !Array.isArray(value)) return [];
    		return value.map(expandRelatedItemData.bind(this)).filter(truthy);
    	} else {
    		return expandRelatedItemData.call(this, value);
    	}
    };

    /**
     * Registers the field on the List's Mongoose Schema.
     */
    relationship.prototype.addToSchema = function () {
    	var field = this;
    	var schema = this.list.schema;
    	var def = {
    		type: this._nativeType,
    		ref: this.options.ref,
    		index: (this.options.index ? true : false),
    		required: (this.options.required ? true : false),
    		unique: (this.options.unique ? true : false),
    	};
    	this.paths = {
    		refList: this.options.refListPath || this._path.append('RefList'),
    	};
    	schema.path(this.path, this.many ? [def] : def);
    	schema.virtual(this.paths.refList).get(function () {
    		return keystone.list(field.options.ref);
    	});
    	if (this.many) {
    		this.underscoreMethod('contains', function (find) {
    			var value = this.populated(field.path) || this.get(field.path);
    			if (typeof find === 'object') {
    				find = find.id;
    			}
    			var result = _.some(value, function (value) {
    				return (value + '' === find);
    			});
    			return result;
    		});
    	}
    	this.bindUnderscoreMethods();
    };

    /**
     * Add filters to a query
     */
    relationship.prototype.addFilterToQuery = function (filter, query) {
    	query = query || {};
    	if (!Array.isArray(filter.value)) {
    		if (typeof filter.value === 'string' && filter.value) {
    			filter.value = [filter.value];
    		} else {
    			filter.value = [];
    		}
    	}
    	if (filter.value.length) {
    		query[this.path] = (filter.inverted) ? { $nin: filter.value } : { $in: filter.value };
    	} else {
    		if (this.many) {
    			query[this.path] = (filter.inverted) ? { $not: { $size: 0 } } : { $size: 0 };
    		} else {
    			query[this.path] = (filter.inverted) ? { $ne: null } : null;
    		}
    	}
    	return query;
    };

    /**
     * Formats the field value
     */
    relationship.prototype.format = function (item) {
    	var value = item.get(this.path);
    	// force the formatted value to be a string - unexpected things happen with ObjectIds.
    	return this.many ? value.join(', ') : (value || '') + '';
    };

    /**
     * Asynchronously confirms that the provided value is valid
     *
     * TODO: might be a good idea to check the value provided looks like a MongoID
     * TODO: we're just testing for strings here, so actual MongoID Objects (from
     * mongoose) would fail validation. not sure if this is an issue.
     */
    relationship.prototype.validateInput = function (data, callback) {
    	var value = this.getValueFromData(data);
    	var result = false;
    	if (value === undefined) {
    		result = true;
    	} else {
    		if (this.many) {
    			if (!Array.isArray(value) && typeof value === 'string' && value.length) {
    				value = [value];
    			}
    			Eif (Array.isArray(value)) {
    				result = true;
    			}
    		} else {
    			if (typeof value === 'string' && value.length) {
    				result = true;
    			}
    			if (typeof value === 'object' && value.id) {
    				result = true;
    			}
    		}
    	}
    	utils.defer(callback, result);
    };

    /**
     * Asynchronously confirms that the provided value is present
     */
    relationship.prototype.validateRequiredInput = function (item, data, callback) {
    	var value = this.getValueFromData(data);
    	var result = false;
    	if (value === undefined) {
    		Iif (this.many) {
    			if (item.get(this.path).length) {
    				result = true;
    			}
    		} else {
    			if (item.get(this.path)) {
    				result = true;
    			}
    		}
    	} else Iif (this.many) {
    		if (!Array.isArray(value) && typeof value === 'string' && value.length) {
    			value = [value];
    		}
    		if (Array.isArray(value) && value.length) {
    			result = true;
    		}
    	} else {
    		if (value) {
    			result = true;
    		}
    	}
    	utils.defer(callback, result);
    };

    /**
     * Validates that a value for this field has been provided in a data object
     *
     * Deprecated
     */
    relationship.prototype.inputIsValid = function (data, required, item) {
    	Eif (!required) return true;
    	if (!(this.path in data) && item && ((this.many && item.get(this.path).length) || item.get(this.path))) return true;
    	if (typeof data[this.path] === 'string') {
    		return (data[this.path].trim()) ? true : false;
    	} else {
    		return (data[this.path]) ? true : false;
    	}
    };

    /**
     * Updates the value for this field in the item from a data object.
     * Only updates the value if it has changed.
     * Treats an empty string as a null value.
     */
    relationship.prototype.updateItem = function (item, data, callback) {
    	if (!(this.path in data)) {
    		return process.nextTick(callback);
    	}
    	Iif (item.populated(this.path)) {
    		throw new Error('fieldTypes.relationship.updateItem() Error - You cannot update populated relationships.');
    	}
    	Iif (this.many) {
    		var arr = item.get(this.path);
    		var _old = arr.map(function (i) { return String(i); });
    		var _new = data[this.path];
    		if (!utils.isArray(_new)) {
    			_new = String(_new || '').split(',');
    		}
    		_new = _.compact(_new);
    		// Only update if the lists aren't the same
    		if (!_.isEqual(_old, _new)) {
    			item.set(this.path, _new);
    		}
    	} else {
    		if (data[this.path]) {
    			Eif (data[this.path] !== item.get(this.path)) {
    				item.set(this.path, data[this.path]);
    			}
    		} else Eif (item.get(this.path)) {
    			item.set(this.path, null);
    		}
    	}
    	process.nextTick(callback);
    };

    /**
     * Returns true if the relationship configuration is valid
     */
    Object.defineProperty(relationship.prototype, 'isValid', {
    	get: function () {
    		return keystone.list(this.options.ref) ? true : false;
    	},
    });

    /**
     * Returns the Related List
     */
    Object.defineProperty(relationship.prototype, 'refList', {
    	get: function () {
    		return keystone.list(this.options.ref);
    	},
    });

    /**
     * Whether the field has any filters defined
     */
    Object.defineProperty(relationship.prototype, 'hasFilters', {
    	get: function () {
    		return (this.filters && _.keys(this.filters).length);
    	},
    });

    /**
     * Adds relationship filters to a query
     */
    // TODO: Deprecate this? Not sure it's used anywhere - JW
    relationship.prototype.addFilters = function (query, item) {
    	_.forEach(this.filters, function (filters, path) {
    		if (!utils.isObject(filters)) {
    			filters = { equals: filters };
    		}
    		query.where(path);
    		_.forEach(filters, function (value, method) {
    			if (typeof value === 'string' && value.substr(0, 1) === ':') {
    				if (!item) {
    					return;
    				}
    				value = item.get(value.substr(1));
    			}
    			query[method](value);
    		});
    	});
    };

    /* Export Field Type */
    module.exports = relationship;