119 lines
2.9 KiB
JavaScript
Raw Normal View History

2016-03-18 11:12:50 +01:00
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
// Public node modules.
const _ = require('lodash');
2016-03-28 18:58:42 +02:00
// Array of supported clients.
const CLIENTS = [
'pg',
'mysql', 'mysql2',
'sqlite3',
'mariasql',
'oracle', 'strong-oracle',
'mssql',
'websql'
];
2016-03-18 11:12:50 +01:00
/**
* Knex hook
*/
module.exports = strapi => {
2016-03-18 11:12:50 +01:00
const hook = {
/**
* Default options
*/
defaults: {
connections: {
default: {
client: 'sqlite3',
debug: false,
acquireConnectionTimeout: 60000,
useNullAsDefault: true,
connection: {
filename: './data/db.sqlite'
},
migrations: {
tableName: 'migrations'
}
}
}
},
/**
* Initialize the hook
*/
initialize: cb => {
2016-03-18 11:12:50 +01:00
strapi.connections = {};
// For each connection in the config register a new Knex connection.
_.forEach(strapi.config.connections, (connection, name) => {
2016-03-18 11:12:50 +01:00
2016-03-28 18:58:42 +02:00
// Make sure we use the client even if the typo is not the exact one.
2016-04-04 22:09:19 +02:00
switch (connection.client) {
2016-03-28 18:58:42 +02:00
case 'postgre':
case 'postgres':
case 'postgresql':
2016-04-04 22:09:19 +02:00
connection.client = 'pg';
break;
2016-03-28 18:58:42 +02:00
case 'sqlite':
2016-04-04 22:09:19 +02:00
connection.client = 'sqlite3';
break;
2016-03-28 18:58:42 +02:00
case 'maria':
case 'mariadb':
2016-04-04 22:09:19 +02:00
connection.client = 'mariasql';
break;
2016-03-28 18:58:42 +02:00
case 'ms':
2016-04-04 22:09:19 +02:00
connection.client = 'mssql';
break;
2016-03-28 18:58:42 +02:00
case 'web':
2016-04-04 22:09:19 +02:00
connection.client = 'websql';
break;
2016-03-28 18:58:42 +02:00
}
// Make sure the client is supported.
if (!_.includes(CLIENTS, connection.client)) {
strapi.log.error('The client `' + connection.client + '` for the `' + name + '` connection is not supported.');
strapi.stop();
}
// Make sure the client is installed in the application
// `node_modules` directory.
2016-03-18 11:12:50 +01:00
try {
require(path.resolve(strapi.config.appPath, 'node_modules', connection.client));
} catch (err) {
strapi.log.error('The client `' + connection.client + '` is not installed.');
strapi.log.error('You can install it with `$ npm install ' + connection.client + ' --save`.');
strapi.stop();
}
2016-03-28 18:58:42 +02:00
// Finally, use the client via `knex`.
// If anyone has a solution to use different paths for `knex` and clients
// please drop us an email at hack@wistity.co-- it would avoid the Strapi
// applications to have `knex` as a dependency.
try {
strapi.connections[name] = require(path.resolve(strapi.config.appPath, 'node_modules', 'knex'))(connection);
} catch (err) {
strapi.log.error('Impossible to use the `' + name + '` connection...');
strapi.log.error(err);
strapi.stop();
}
2016-03-18 11:12:50 +01:00
});
cb();
}
};
return hook;
};