/**
 * 车场镜像库
 */

import { logger } from "mslib";
import { Container } from "typescript-ioc";
import Contants from "./Contants";

/**
 * 镜像车场knex实例
 * 
 * 模块被加载时，从ioc读取配置config.parkImageKnex并自动创建该实例，如果未配置则为空
 * 
 * 具体配置参考官方文档
 * 
 * https://www.npmjs.com/package/knex
 */
export let knexInstance = null;

let config = Container.getValue('config.parkImageKnex');
if (config) {
    knexInstance = generateMySqlKnexInstance(config);
}

export function generateMySqlKnexInstance(config) {
    const defaults = {
        client: 'mysql2',
        pool: { min: 0, max: 7 },
        debug: !Contants.IS_PROD,
        acquireConnectionTimeout: 5000,
        log: {
            warn(message) {
                logger.warn(message);
            },
            error(message) {
                logger.error(message);
            },
            deprecate(message) {
                logger.error(message);
            },
            debug(message) {
                logger.debug(message);
            },
        }
    };

    return require('knex')(Object.assign(defaults, config));
}