node-query/lib/NodeQuery.js

77 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-12-07 15:58:31 -05:00
'use strict';
const helpers = require('./helpers');
const QueryBuilder = require('./QueryBuilder');
// Map config driver name to code class name
const dbDriverMap = new Map([
['my', 'Mysql'],
['mysql', 'Mysql'],
['maria', 'Mysql'],
['mariadb', 'Mysql'],
['firebird', 'Firebird'],
['postgresql', 'Pg'],
['postgres', 'Pg'],
['pg', 'Pg'],
['sqlite3', 'Sqlite'],
['sqlite', 'Sqlite'],
]);
/**
* Class for connection management
*
* @param {object} config - connection parameters
*/
class NodeQuery {
/**
* Constructor
*
* @param {object} config - connection parameters
* @example let nodeQuery = require('ci-node-query')({
* driver: 'mysql',
* connection: {
* host: 'localhost',
* user: 'root',
* password: '',
* database: 'mysql'
* }
* });
* @example let nodeQuery = require('ci-node-query')({
* driver: 'sqlite',
* connection: ':memory:'
* });
*/
constructor(config) {
this.instance = null;
if (config != null) {
let drivername = dbDriverMap.get(config.driver);
2016-03-11 16:32:38 -05:00
if (! drivername) {
throw new Error(`Selected driver (${config.driver}) does not exist!`);
}
let driver = require(`./drivers/${drivername}`);
let $adapter = require(`./adapters/${drivername}`);
let adapter = new $adapter(config.connection);
this.instance = new QueryBuilder(driver, adapter);
}
}
/**
* Return an existing query builder instance
*
* @return {QueryBuilder} - The Query Builder object
*/
getQuery() {
2015-12-07 12:03:42 -05:00
if (this.instance == null) {
2015-12-07 15:58:31 -05:00
throw new Error('No Query Builder instance to return');
}
return this.instance;
}
}
module.exports = (config => new NodeQuery(config));