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


//严格模式
/*-------------------------------------------------------------------------------------------*/	
    'use strict';
/*-------------------------------------------------------------------------------------------*/	
    
const MongoClient = require('mongodb').MongoClient;
const Server = require('mongodb').Server;

//mongo 初始化
/*-------------------------------------------------------------------------------------------*/	    
    
class db_mongo
{
    static async con() 
    {	
        const cdb=$DbMongo.$opt
        for (const key in cdb) 
        {
            let cur=cdb[key]
            let res,resNav;
            try 
            {
                let beg=new MongoClient
                (
                    new Server
                    (
                        cur['host'],
                        cur['port'],
                        cur['option'],
                        cur['server']
                    )
                );
                res=await beg.connect()
                resNav=res
                res=res.db(cur['db'])
            } 
            catch (error) 
            {
                console.error(`MONGO进程：`+process.pid+`------链接错误[${key}]+${error.stack}`);
                return;  
            }
            console.info(`MONGO进程：`,process.pid+`------链接成功[${key}]`);
            $DbMongo.$con[key]=res;
            $DbMongo.$con[key].session=resNav
        }
    }

    static async transaction(fun,db='main')
	{
        let session;
		try 
		{
			// 开启事务
            session = $DbMongo.$con[db].session.startSession()
            await session.startTransaction()
            let data= await fun({session})
            await session.commitTransaction();
			return (typeof data != 'undefined')?data:true;
		} 
		catch (error) 
		{
            if(session)await session.abortTransaction(1);   
            console.error('[mongo事物]出错',error)
            throw Error('[mongo]事物中断')
        }
        finally
        {
            if(session)await session.endSession(); 
        }
	}

    static id(da)
    {
        return require('mongodb').ObjectID(da);  
    }
}

module.exports=db_mongo;