'use strict';
/*
 *@decription 公共数据统一管理
 *@author xtx1130
 *@memo 每一个koax实例会相应的维护一套数据
*/

const rp = require('request-promise');
//const tough = require('tough-cookie');
const assert = require('assert');
const isEmptyObj = require('../../deps/isEmptyObj');

class koax {
	constructor(){
		this.data = {};
		this.nameCache = void 0;
		this.dataCache = {};
	}
	//设置cookie 不做了，cookie独立出来一个类，也可以加到request中
	// setCookie(){
	// 	return this;
	// }
	//设置数据的key
	setName(name){
		assert(!this.data[name],'this name has been declared.');
		this.data[name]={};
		this.nameCache = name;
		return this;
	}
	/*
	 *@description request请求接口，这里数据挂载到data视图上，
		async为以后多请求做准备 name 可不加，链式调用的时候name做缓存，取最近声明的name
		important: 因为为async函数，所以一定要放到链式最后调用，如果觉得不方便，以后改成use的形式
	*/
	async request(options, name) {
		let tplName = name || this.nameCache;
		assert(tplName, 'no name has been declared.');
		if (this.dataCache[tplName] && !isEmptyObj(this.data[tplName])) {
			return this;
		}
		try {
			let res = await rp(options);
			this.data[tplName] = res;
		} catch (e) {
			throw e;
		}
		return this;
	}
	/*
	 *@description 为request请求添加缓存，防止下一次请求的时候进行http调用
	*/
	cached(name) {
		let tplName = name || this.nameCache;
		this.dataCache[tplName] = true;
		return this;
	}
	//返回供koas调用的中间件，这里data挂在到ctx上
	middleware(){
		let _this = this;
		let dispatch = async (ctx,next) => {
			ctx.koax = ctx.koax||{};
			let copy = Object.assign(ctx.koax,_this.data);
			await next();
		}
		return dispatch;
	}
}
exports = module.exports = koax;
@@ -126,49 +126,8 @@
 ');%0A
-//const tough = require('tough-cookie');%0A
 cons
@@ -314,93 +314,8 @@
 %0A%09%7D%0A
-%09//%E8%AE%BE%E7%BD%AEcookie %E4%B8%8D%E5%81%9A%E4%BA%86%EF%BC%8Ccookie%E7%8B%AC%E7%AB%8B%E5%87%BA%E6%9D%A5%E4%B8%80%E4%B8%AA%E7%B1%BB%EF%BC%8C%E4%B9%9F%E5%8F%AF%E4%BB%A5%E5%8A%A0%E5%88%B0request%E4%B8%AD%0A%09// setCookie()%7B%0A%09// %09return this;%0A%09// %7D%0A
 %09//%E8%AE%BE
@@ -901,16 +901,32 @@
  = res;%0A
+%09%09%09return this;%0A
 %09%09%7D catc
@@ -949,31 +949,16 @@
  e;%0A%09%09%7D%0A
-%09%09return this;%0A
 %09%7D%0A%09/*%0A%09

delete cookie apis