'use strict';
const { ClickHouse } = require('clickhouse');

function factory (app, opts) {
   if (opts.clickHouse) {
      try {
         app.fs.clickHouse = {}
         const { url, port, user, password, db = [] } = opts.clickHouse
         for (let d of db) {
            if (d.name && d.db) {
               app.fs.clickHouse[d.name] = new ClickHouse({
                  url: url,
                  port: port,
                  debug: opts.dev,
                  format: "json",
                  basicAuth: user && password ? {
                     username: user,
                     password: password,
                  } : null,
                  config: {
                     database: d.db,
                  },
               })
               console.info(`ClickHouse ${d.name} 初始化完成`);
            } else {
               throw 'opts.clickHouse 参数错误!'
            }
         }
      } catch (error) {
         console.error(error)
         process.exit(-1);
      }
   }
}

module.exports = factory;