Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
b9abc72
Initial commit
May 24, 2019
738afab
develop files
May 24, 2019
8ceaaf3
Unit tests
May 27, 2019
b500d40
Development and fixes
May 27, 2019
7c5afc2
Updated README
May 27, 2019
a044d5d
Unnecessary instance methods converted to static
May 27, 2019
bc7f36f
Fixed test for static methods
May 27, 2019
74565ab
Updated docs
May 27, 2019
38f2fb4
Fixed readme
May 27, 2019
14e5983
Fixed readme
May 27, 2019
c22f517
DBDrivers packages are now optional
May 28, 2019
4422287
Unit tests updated
May 28, 2019
b3a1e88
Removed dbdrivers dependencies
May 28, 2019
c50f678
Updated readme
May 28, 2019
7182d81
Fixed cwd modules require
May 28, 2019
ec83f75
Updated tests
May 28, 2019
86195cb
Updated changelog
May 28, 2019
6def940
Updated docs
May 29, 2019
3a1c736
travis badges implemetation
May 29, 2019
9c75728
travis badges implemetation
May 29, 2019
a4464fc
Fixed config file path
May 30, 2019
6b956ff
Updated docs
Jun 4, 2019
e6616d7
Optimized tests
Jun 4, 2019
1d474ec
Config docs
Jun 10, 2019
677899a
Fixed docs
Jun 10, 2019
728e619
Fixed docs examples
Jun 10, 2019
bcd0330
Fixed docs
Jun 11, 2019
8d74072
Required/optional indications for config file keys
Jun 11, 2019
17944bd
Minor code fixes and simplifications
Jun 11, 2019
40ba835
Updated tests
Jun 11, 2019
b17dcaf
Improved tests
Jun 11, 2019
fbcb339
Removed unused sinon package
Jun 11, 2019
8f13b9c
Config file datatype checkouts
Jun 11, 2019
9484dde
Invalid config error
Jun 11, 2019
7fd27b0
Updated tests
Jun 11, 2019
d86b827
Updated docs
Jun 11, 2019
81c9970
Updated docs
Jun 11, 2019
17f13ab
Updated tests
Jun 11, 2019
c543201
Invalid db type config error
Jun 11, 2019
300f039
config validator and set config methods
Jun 11, 2019
c5bd6e2
Updated docs
Jun 12, 2019
2ba071d
DB type not found in config new error code
Jun 12, 2019
5a8e6dd
Converted to static and optimized config methods
Jun 12, 2019
2138148
Updated tests
Jun 12, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
'use strict';

module.exports = {
extends: 'airbnb-base',

env: {
node: true,
es6: true,
mocha: true
},

globals: {
__rootpath: true,
coreRequire: true,
mainRequire: true,
JANIS_CORE: true,
JANIS_ENV: true,
JANIS_ENV_ALIAS: true
},

parserOptions: {
sourceType: 'script'
},

rules: {
'operator-linebreak': 0,
'no-continue': 0,
'no-plusplus': 0,
'prefer-spread': 0,
'prefer-rest-params': 0,
'class-methods-use-this': 0,
'consistent-return': 0,
'prefer-template': 0,
'import/no-unresolved': 0,
'import/no-extraneous-dependencies': ['error', { devDependencies: ['**/tests/**/*.js'] }],

'no-bitwise': 0,

curly: ['error', 'multi-or-nest'],

'no-underscore-dangle': ['warn', {
allowAfterThis: true,
allowAfterSuper: true,
allow: ['_call', '__rootpath', '_where']
}],

'no-tabs': 0,

'no-new': 0,

'func-names': 0,

'space-before-function-paren': ['error', 'never'],

'arrow-parens': ['error', 'as-needed'],
'arrow-body-style': 0,

indent: ['error', 'tab', {
SwitchCase: 1
}],

'comma-dangle': ['error', 'never'],

'padded-blocks': 0,

'max-len': ['error', {
code: 150,
tabWidth: 1,
comments: 200
}],

'spaced-comment': ['error', 'always', {
exceptions: ['*']
}],

'newline-per-chained-call': ['error', {
ignoreChainWithDepth: 2
}],

'no-param-reassign': 0,

'no-prototype-builtins': 0,

'keyword-spacing': ['error', {
overrides: {
if: {
after: false
},
for: {
after: false
},
while: {
after: false
},
switch: {
after: false
},
catch: {
after: false
}
}
}],

'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'function-paren-newline': 0,
'no-await-in-loop': 0,

'object-curly-newline': ['error', {
ObjectExpression: { minProperties: 5, multiline: true, consistent: true },
ObjectPattern: { minProperties: 5, multiline: true, consistent: true }
}],
'nonblock-statement-body-position': ['error', 'below', { overrides: { else: 'any' } }]
}
};
19 changes: 19 additions & 0 deletions .nycrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"exclude": [
"tests/",
"mocks/",
".eslintrc.js",
".travis.yml"
],
"extension": [
".js"
],
"cache": true,
"all": true,
"default-excludes": true,
"check-coverage": true,
"statements": 95,
"branches": 95,
"functions": 95,
"lines": 95
}
15 changes: 15 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
language: node_js
node_js:
- "lts/*"
cache: npm
script:
- |
# Run test script
npm run test-ci
after_script:
- |
# Upload coverage to coveralls
if [[ -d .nyc_output ]]; then
npm install --save-dev coveralls@2
nyc report --reporter=text-lcov | coveralls
fi
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added
- `Database dispatcher package`
- `Unit tests`
- `Docs`
- `badges in readme`
- `Invalid config error`
- `Invalid db type in config error`
- `Config validation methods`

### Fixes
- `Fixed error while loading database drivers dependencies`
- `Fixed config file path`
121 changes: 120 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,120 @@
# database-dispatcher
# database-dispatcher

[![Build Status](https://travis-ci.org/janis-commerce/database-dispatcher.svg?branch=JCN-68-database-dispatcher)](https://travis-ci.org/janis-commerce/database-dispatcher)
[![Coverage Status](https://coveralls.io/repos/github/janis-commerce/database-dispatcher/badge.svg?branch=JCN-68-database-dispatcher)](https://coveralls.io/github/janis-commerce/database-dispatcher?branch=JCN-68-database-dispatcher)

**DatabaseDispatcher** is a package that returns the necessary DB driver from a received model. Access to the databases configuration then returns the driver instance with the connection. It caches the connections and configs.

## Installation

```sh
npm install @janiscommerce/database-dispatcher

# Then install all the drivers that you need.
npm install --save @janiscommerce/mysql
npm install --save @janiscommerce/mongodb
```

## Configs

This package requires a config file: `/path/to/root/config/database.json`

### Structure

- Root key: the model `databaseKey`
Includes the driver type and connections settings.

```js
{
"databaseKey": {
"type": "mysql"
// ...
}
}
```

Keys

- `type [String]` (required): Database driver type, example `"mysql"`.
- `host [String]` (required): Database connection host.
- `port [Number]` (required): Database connection port.
- `user [String]` (optional): Database login user name.
- `password [String]` (optional): Database login password.
- `database [String]` (required): Database name for connection, example `"myDB"`.
- `connectionLimit [Number]` (optional): Connection limit.
- `prefix [String]` (optional): Prefix for values.

### Example

```json
{
"core": {
"type": "mysql",
"host": "localhost",
"user": "root",
"database": "myDB",
"port": 3306
},
"services": {
"type": "mongodb",
"host": "mongodb://localhost",
"user": "sarasa",
"password": "foobar",
"database": "myDB",
"port": 27017
}
}
```

## API

- `config`
Returns the loaded database config json.
- `getDatabase("databaseKey")`
Receives the database key `[String]` then returns the database driver instance with the connection from the config json.
If the `databaseKey` not exists on the config json will throw a `DatabaseDispatcherError`.
The default value of `databaseKey` parameter is `"_default"`.
- `clearCaches()`
Clear all caches, including configs and DB connections.

## Errors

The errors are informed with a `DatabaseDispatcherError`.
This object has a code that can be useful for a correct error handling.
The codes are the following:

| Code | Description |
|------|------------------------------------|
| 1 | Config not found |
| 2 | Invalid databaseKey |
| 3 | Database driver not installed |
| 4 | Invald config |
| 5 | Invalid db type in config |
| 6 | DB type setting not found in config|

## Usage

```js
const DatabaseDispatcher = require('@janiscommerce/database-dispatcher');

const DBConfig = DatabaseDispatcher.config;

/*
core: {
type: 'mysql',
host: 'foo',
...
},
services: {
type: 'mongodb',
host: 'foo',
...
}
*/

const myDBConnection = DatabaseDispatcher.getDatabase('core'); // A new DBDriver instance is returned.

let fields = myDBConnection.get(model, { item: 'sarasa' }); // should connect to db driver and return the items...

DatabaseDispatcher.clearCaches(); // cached connections and configs cleared.
```
25 changes: 25 additions & 0 deletions database-dispatcher/database-dispatcher-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';

class DatabaseDispatcherError extends Error {

static get codes() {

return {
CONFIG_NOT_FOUND: 1,
INVALID_DB_KEY: 2,
DB_DRIVER_NOT_INSTALLED: 3,
INVALID_CONFIG: 4,
INVALID_DB_TYPE_CONFIG: 5,
CONFIG_DB_TYPE_NOT_FOUND: 6
};
}

constructor(err, code) {
super(err);
this.message = err.message || err;
this.code = code;
this.name = 'DatabaseDispatcherError';
}
}

module.exports = DatabaseDispatcherError;
Loading