excellent.js 8.4 KB
var urlencode = require('urlencode');

exports = module.exports = function (logger, rest, redis, settings) {
	function getOptions(url, type) {
		var catalog = url.substring(1, url.indexOf('/', 1));
		var pathUrl = url.substring(url.indexOf('/', 1));
		var fullPath = '/' + catalog + settings.excellentRestful.version + pathUrl;
		return {
			'host': settings.excellentRestful.host, //后台请求地址
			'port': settings.excellentRestful.port,
			'path': fullPath,
			'method': type,
			'agent': false,
			'headers': {
				"Accept": "application/json",
				"Content-Type": "application/json",
				'Proxy-User-Agent': 'Request for Express'
			}
		};
	}

	async function addToken(options, req) {
		if (req.session.passport && req.session.passport.user && req.session.passport.user && req.session.passport.user.user_info) {
			const yxly_token = await redis.get(`${req.session.passport.user.user_info.user.id}_yxly_token`)
			if (yxly_token) {
				options.headers['Authorization'] = yxly_token ? `Bearer ${yxly_token}` : '';
			}
		}

		if (req.headers['device-id']) {
			options.headers['Device-Id'] = req.headers['device-id']
		}
		if (req.ip) {
			options.headers['Client-Ip'] = req.ip
		}
		if (req.headers['x-request-id']) {
			options.headers['X-Request-Id'] = req.headers['x-request-id']
		}
		if(req.headers['user-agent'] ){
			options.headers['User-Agent'] = req.headers['user-agent']
		} 

		return options;
	}

	function addReqResOptions(options, req,res){
		options['req']=req;
		options['res']=res;
		return options;
	}

	function addParams(options, req) {
		var postData = !req.body ? '' : JSON.stringify(req.body || {});
		// options.headers['Content-Length'] = postData.length;
		options.params = postData;
	}

	function addContentLength(options) {
		if (options.params) {
			options.headers['Content-Length'] = options.params.length;
		}
	}

	function encodeUrl(url) {
		return urlencode(url);
	}

	function encodePamars(params) {
		var temp = [];
		for (var i = 0; i < params.length; i++) {
			var param = params[i];
			var tempParam = param.split("=")
			tempParam[1] = urlencode.decode(tempParam[1], 'utf8');
			tempParam[1] = tempParam[1].replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');

			if (i < (params.length - 1)) {
				if (/[:&+/?%#=]/g.test(tempParam[1])) {
					temp.push(tempParam[0] + "=" + encodeUrl(tempParam[1]) + "&");
				} else {
					temp.push(tempParam[0] + "=" + tempParam[1] + "&");
				}
			} else {
				if (/[:&+/?%#=]/g.test(tempParam[1])) {
					temp.push(tempParam[0] + "=" + encodeUrl(tempParam[1]));
				} else {
					temp.push(tempParam[0] + "=" + tempParam[1]);
				}
			}
		}
		return temp.join("");
	}

	function handlePamars(url) {
		var tempUrl = url;
		// if(url.indexOf("?")!=-1){
		// 	var temp=url.split("?");
		// 	var params=""; 
		// 	if(temp[1]&&temp[1].indexOf("&")!=-1){
		// 		params=encodePamars(temp[1].split("&"));
		// 	}else{
		// 		params=encodePamars([temp[1]]);
		// 	}
		// 	return temp[0]+"?"+params;
		// }else {
		// 	return tempUrl;
		// } 
		return tempUrl;
	}

	function splitServiceFromUrl(url) {
		var catalog = url.substring(1, url.indexOf('/', 1));
		var pathUrl = url.substring(url.indexOf('/', 1));
		var fullPath = settings.restful.url + catalog + settings.restful.version + pathUrl;
		return fullPath
	}

	function splitUrl(fullUrl) {
		if (settings.prefix && settings.prefix.length > 1) {
			fullUrl = fullUrl.substring(settings.prefix.length - 1);
		}
		var url = fullUrl.substring(fullUrl.indexOf('/', 1));
		return url;
	}

	function searchService(services, name) {
		if (services[name]) {

			return false;
		} else {
			return true;
		}
	}

	function checkReq(req, res) {
		var flag = true;
		// if(flag&&req.headers&&!req.headers['service-catalog']){
		// 	res.status(400);
		// 	res.send({"errors":{},"message":"缺少必要请求参数,服务目录名称是必填项"}); 
		// 	flag=false;
		// }
		// if(flag&&req.session.passport&&req.session.passport.user&&!req.session.passport.user.service_catalog){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未加载,请重新登录"}); 
		// 	flag=false;
		// }
		// if(flag&&searchService(req.session.passport.user.service_catalog,req.headers['service-catalog'])){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未查询到请求服务,请确认参数正确"}); 
		// 	flag=false; 
		// }
		return flag;
	}

	function checkJson(req) {
		if (req.headers && req.headers['content-type'] == 'application/json') {
			return true;
		} else {
			return false;
		}
	}

	async function get(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'GET');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		function _success(data, response) {
			if (response.statusCode >= 400 || !data) {
				logger.debug(options, data);
				res.status(response.statusCode);
				res.send(data);
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	async function post(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'POST');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		addParams(options, req);
		function _success(data, response) {
			if (response.statusCode >= 400) {
				logger.debug(options, data);
				res.status(response.statusCode);
				res.send(data);
			} else if (!data || 'null' == data || "null\n" == data || '{}' == data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	async function put(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'PUT');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		addParams(options, req);
		function _success(data, response) {
			if (response.statusCode >= 400) {
				logger.debug(options, data);
				res.status(response.statusCode);
				res.send(data);
			} else if (!data || 'null' == data || "null\n" == data || '{}' == data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	async function patch(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'PATCH');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		addParams(options, req);
		function _success(data, response) {
			if (response.statusCode >= 400) {
				logger.debug(options, data);
				res.send(data);
			} else if (!data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	async function head(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'HEAD');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		addParams(options, req);
		function _success(data, response) {
			if (response.statusCode >= 400) {
				logger.debug(options, data);
				res.send(data);
			} else if (!data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	async function del(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'DELETE');
		await addToken(options, req);
		addReqResOptions(options, req,res);
		addParams(options, req);
		addContentLength(options);
		function _success(data, response) {
			if (response.statusCode >= 400) {
				logger.debug(options, data);
				res.status(response.statusCode);
				res.send(data);
			} else if (!data || (data && !data.message)) {
				res.send({
					code: 200,
					action: "delete",
					message: '删除成功'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.debug(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	return {
		'get': get,
		'post': post,
		'put': put,
		'patch': patch,
		'head': head,
		'delete': del
	};
};

exports['@singleton'] = true;
exports['@require'] = ['igloo/logger', 'utils/rest', 'utils/redis', 'igloo/settings'];