`

基于elasticsearch Rest URL模板动态生成(索引按照日期切分)

阅读更多
例如,
日期: 2014-09-11至2014-09-12
Template: http://192.168.0.1:9200/{repeat:(prefix, dayslot, suffix)}/_search

调用方式:
  var urlcomplie = new shyl.view.esreport.ux.EsUrlCompiler(url),
  url = urlcomplie.getValue(options);//options = {dayslot: [20140911, 20140912]} 日期需要处理好

结果 url= http://192.168.0.1:9200/prefix20140911suffix,prefix20140912suffix, /_search


/**
* url 模板编译类, 基于ES RESTFul定制数据源时, 它的URL配置往往是需要支持动态生成的,
* 所以该类主要用来处理URL的模板部分例如:
* http://host:port/{指令名称:(参数值)}/{指令名称:(参数值)}。
* 基于这样的设计,你可以定义自己想要的格式。
*
* @author wang xiu fu
*/
Ext.define('shyl.view.esreport.ux.EsUrlCompiler', {
	requires: [],
	/**
	 * 匹配模板表达式
	 */
	re: /\{([\w]+)(?:\:)\(([\w,]+)?\)\}/g,
	
	url: null,
	
	complied: Ext.emptyFn,
	
	commands: {
		repeat: true
	},
	
	isUrlCompiler: true,
	
	constructor: function(url, options) {
		options = options || {};
		Ext.apply(this, options);
		this.complie(url);
		
	},
	
	complie: function(url) {
		var me=this,
			bodyReturn,
			body;
		function fn (m, command, params) {
			if (!me.commands[command]) {
				Ext.Error.raise('url模板中的"+command+"不存在');
			}
			params = params || '';
			var params = params.split(','),
				len = params.length,
				prefix = '',
				suffix = '',
				array = '',
				i;
			switch(len) {
				case 1:
					array = "this['" + params[0] + "']";
					break;
				case 2:
					prefix = "'" + params[0] + "',";
					array = "this['" + params[1] + "']";
					break;
				case 3:
					prefix = "'" + params[0] + "'";
					array = "this['" + params[1] + "']";
					suffix = ",'" + params[0] + "'";
					break;
			}
			return "' + this." + command + "(" + prefix + array + suffix +") + '";
		}
		bodyReturn = "'" + url.replace(me.re, fn) + "'";
		body = "this.complied = function() { return " + bodyReturn + "; }";
		eval(body);
		return me;
	},
	
	getValue: function(options) {
		options = options || {};
		if (Ext.isFunction(options)) {
			options = options();
		} 
		Ext.apply(this, options);
		return this.complied();
	},
	
	//---------------------------------command-----------------------------------------------
	/**
	 * 重复指令,该参数有个参数
	 * 
	 */
	repeat: function(prefix, array, suffix) {
		var me=this,
			prefix = prefix || "",
			suffix = suffix || "",
			array = array || [],
			i;
		if (!array || !array.length || array.length === 0) {
			throw new Error('url模板包含错误的参数');
		}
		for (i in array) {
			array[i] = prefix + array[i] + suffix;
		}
		return array.join(',');
	}
	//其他其他指令可以在此扩展
});
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics