all files / keystone/fields/types/text/ TextType.js

100% Statements 37/37
100% Branches 25/25
100% Functions 5/5
100% Lines 37/37
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             14× 14× 14× 14×     11× 11× 11×                                      
var FieldType = require('../Type');
var util = require('util');
var utils = require('keystone-utils');
 
/**
 * Text FieldType Constructor
 * @extends Field
 * @api public
 */
function text (list, path, options) {
	this._nativeType = String;
	this._properties = ['monospace'];
	this._underscoreMethods = ['crop'];
	text.super_.call(this, list, path, options);
}
util.inherits(text, FieldType);
 
text.prototype.validateInput = function (data, callback) {
	var value = this.getValueFromData(data);
	var result = value === undefined || value === null || typeof value === 'string';
	utils.defer(callback, result);
};
 
text.prototype.validateRequiredInput = function (item, data, callback) {
	var value = this.getValueFromData(data);
	var result = !!value;
	if (value === undefined && item.get(this.path)) {
		result = true;
	}
	utils.defer(callback, result);
};
 
/**
 * Add filters to a query
 */
text.prototype.addFilterToQuery = function (filter, query) {
	query = query || {};
	if (filter.mode === 'exactly' && !filter.value) {
		query[this.path] = filter.inverted ? { $nin: ['', null] } : { $in: ['', null] };
		return query;
	}
	var value = utils.escapeRegExp(filter.value);
	if (filter.mode === 'startsWith') {
		value = '^' + value;
	} else if (filter.mode === 'endsWith') {
		value = value + '$';
	} else if (filter.mode === 'exactly') {
		value = '^' + value + '$';
	}
	value = new RegExp(value, filter.caseSensitive ? '' : 'i');
	query[this.path] = filter.inverted ? { $not: value } : value;
	return query;
};
 
/**
 * Crops the string to the specifed length.
 */
text.prototype.crop = function (item, length, append, preserveWords) {
	return utils.cropString(item.get(this.path), length, append, preserveWords);
};
 
/* Export Field Type */
module.exports = text;