
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/
    
// 会话操作
/*-------------------------------------------------------------------------------------------*/	
	class session
	{	
		constructor(req)
		{
			this.sessionCookie='$session-'+req.sessionCookie
		}

		async set(key,value,time=$Config.sessionTime)
		{
			let id=this.sessionCookie
			if(!id)
			{
				console.error('SESSION服务------请求失败，未传ID');
				return false;
			}
			let result= await $DbRedis.$con['main'].pipeline
			(
				[
					['hset',id, key,value],
					['expire',id, time]
				]
			).exec(); 
			return {'hset':result[0][1],'expire':result[1][1]}
		}

		async sets(obj,time=$Config.sessionTime)
		{
			if(typeof obj != 'object')return {}
			let id=this.sessionCookie
			let arr=[]
			for (const iterator in obj) 
			{
				arr.push(iterator)
				arr.push(obj[iterator])
			}

			if(!id)
			{
				console.error('SESSION服务------请求失败，未传ID');
				return false;
			}
			let result= await $DbRedis.$con['main'].pipeline
			(
				[
					['hmset',id, ...arr],
					['expire',id, time]
				]
			).exec(); 
			return {'hset':result[0][1],'expire':result[1][1]}
		}

		async get(key,time=$Config.sessionTime)
		{
			let id=this.sessionCookie
			if(!id || !key)
			{
				console.warn('SESSION服务------请求失败，未传ID或者KEY');
				return null;
			}
			let data=await $DbRedis.$con['main'].hget(id,key);

			if(data)
			{
				await $DbRedis.$con['main'].expire(id,time);
				return {[key]:data};
			}
			else
			{
				return null;
			}
		}

		async gets(key,time=$Config.sessionTime)
		{
			if(typeof key != 'object')return {}
			let id=this.sessionCookie
			if(!id || !key)
			{
				console.warn('SESSION服务------请求失败，未传ID或者KEY');
				return {};
			}
			
			let data=await $DbRedis.$con['main'].hmget(id,...key);
			let obj={}
			if(data)
			{
				for (let index = 0; index < key.length; index++) 
				{
					obj[key[index]]=data[index]
				}
				await $DbRedis.$con['main'].expire(id,time);
				return obj;
			}
			else
			{
				return {};
			}
		}

		async del(key)
		{
			let id=this.sessionCookie
			if(!id)
			{
				console.error('SESSION服务------请求失败，未传ID');
				return false;
			}
			let res
			if(key)
			{
				res= await $DbRedis.$con['main'].hdel(id,key);
			}
			else
			{
				res= await $DbRedis.$con['main'].del(id);
			}
			return res;
		}

  }
/*-------------------------------------------------------------------------------------------*/    
module.exports=session;