all files / keystone/lib/list/ getData.js

12.5% Statements 3/24
0% Branches 0/18
0% Functions 0/2
12.5% Lines 3/24
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                                                                                        
var listToArray = require('list-to-array');
 
/**
 * Gets the data from an Item ready to be serialised for client-side use, as
 * used by the React components
 */
 
function getData (item, fields, expandRelationshipFields) {
	var data = {
		id: item.id,
		name: this.getDocumentName(item),
	};
	if (this.autokey) {
		data[this.autokey.path] = item.get(this.autokey.path);
	}
	if (this.options.sortable) {
		data.sortOrder = item.sortOrder;
	}
	if (fields === undefined) {
		fields = Object.keys(this.fields);
	}
	if (fields) {
		if (typeof fields === 'string') {
			fields = listToArray(fields);
		}
		if (!Array.isArray(fields)) {
			throw new Error('List.getData: fields must be undefined, a string, or an array.');
		}
		data.fields = {};
		fields.forEach(function (path) {
			var field = this.fields[path];
			if (field) {
				if (field.type === 'relationship' && expandRelationshipFields) {
					data.fields[path] = field.getExpandedData(item);
				} else {
					data.fields[path] = field.getData(item);
				}
			} else {
				data.fields[path] = item.get(path);
			}
		}, this);
	}
	return data;
}
 
module.exports = getData;