Skip to content

Commit d5139b2

Browse files
authored
Initial commit
0 parents  commit d5139b2

File tree

8 files changed

+403
-0
lines changed

8 files changed

+403
-0
lines changed

.github/workflows/npm-publish.yml

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2+
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
3+
4+
name: Node.js Package
5+
6+
on:
7+
push:
8+
branches:
9+
- master
10+
release:
11+
types: [created]
12+
13+
jobs:
14+
build:
15+
runs-on: ubuntu-latest
16+
steps:
17+
- uses: actions/checkout@v2
18+
- uses: actions/setup-node@v1
19+
with:
20+
node-version: 12
21+
- run: yarn
22+
# - run: npm test
23+
24+
publish-npm:
25+
needs: build
26+
runs-on: ubuntu-latest
27+
steps:
28+
- uses: actions/checkout@v2
29+
- uses: actions/setup-node@v1
30+
with:
31+
node-version: 12
32+
registry-url: https://registry.npmjs.org/
33+
- run: yarn
34+
- run: yarn publish
35+
env:
36+
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}

.gitignore

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Use yarn.lock instead
2+
package-lock.json
3+
4+
# Environment variables
5+
.env
6+
7+
# Logs
8+
logs
9+
*.log
10+
npm-debug.log*
11+
12+
# Runtime data
13+
pids
14+
*.pid
15+
*.seed
16+
17+
# Directory for instrumented libs generated by jscoverage/JSCover
18+
lib-cov
19+
20+
# Coverage directory used by tools like istanbul
21+
coverage
22+
23+
# nyc test coverage
24+
.nyc_output
25+
26+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
27+
.grunt
28+
29+
# node-waf configuration
30+
.lock-wscript
31+
32+
# Compiled binary addons (http://nodejs.org/api/addons.html)
33+
build/Release
34+
35+
# Dependency directories
36+
node_modules
37+
jspm_packages
38+
39+
# Optional npm cache directory
40+
.npm
41+
42+
# Optional REPL history
43+
.node_repl_history
44+
45+
# Logs
46+
yarn-error.log
47+
error.log
48+
combined.log
49+
database.log
50+
perf.log
51+
http.log
52+
53+
# IDE
54+
.idea

.npmrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
@softrams:registry=https://registry.npmjs.org

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2020 Softrams
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# MySQL DB Connector
2+
3+
Wrapper utility to easily manage multiple data sources and pooled connections.
4+
5+
## Error Returns
6+
7+
By default, all errors occurring during a query are returned. If you want to be extra-safe in a production environment, you can set `HIDE_DB_ERRORS` value on the root `config` passed to the connector on initialization. When you do this, all errors will be logged, but none returned when a query error occurs.
8+
9+
## SSL Settings
10+
11+
This connector allows setting SSL connection using a few different options.
12+
13+
You can provide a custom cert:
14+
15+
```
16+
SSL: {
17+
CUSTOM_CERT: // custom cert string
18+
}
19+
```
20+
21+
By default, when specifying an SSL object, the mysql connector will reject unauthorized calls by adding `rejectUnauthorized: true`. You may override this setting by specifying a value for `REJECT_UNAUTHORIZED` in your `SSL` config:
22+
23+
```
24+
SSL: {
25+
REJECT_UNAUTHORIZED: false // not recommended
26+
}
27+
```
28+
29+
#Data Typing Options
30+
31+
This connector gives you a few options for configuring how data is returned from the connector. 'typeCast' defaults to true, and converts
32+
data from the database to its javascript equivalent. For example, it will convert DATETIME SQL objects to a DATE javascript type.
33+
You can also set 'dateStrings' which defaults to false. If you set it to true it will override typeCast and force date returns to be a string instead of a DATE type.

index.js

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
/* istanbul ignore file */
2+
/* eslint-disable no-restricted-syntax */
3+
/* eslint-disable no-await-in-loop */
4+
/* eslint-disable no-else-return */
5+
const mysql = require("mysql");
6+
const fs = require('fs');
7+
8+
let pools = {};
9+
let config = {};
10+
const genericError = 'An error occurred communicating with the database.';
11+
12+
exports.init = async (cfg) => {
13+
config = cfg;
14+
};
15+
16+
exports.createPool = async (poolName) => {
17+
try {
18+
const srcCfg = config.DATASOURCES[poolName];
19+
if (srcCfg) {
20+
const options = {
21+
connectionLimit: srcCfg.DB_CONNECTION_LIMIT || 5,
22+
host: srcCfg.DB_HOST,
23+
user: srcCfg.DB_USER,
24+
password: srcCfg.DB_PASSWORD,
25+
database: srcCfg.DB_DATABASE,
26+
port: srcCfg.PORT,
27+
multipleStatements: srcCfg.ALLOW_MULTI_STATEMENTS || false,
28+
timezone: srcCfg.TIMEZONE || 'local',
29+
typeCast: srcCfg.TYPE_CAST || true,
30+
dateStrings: srcCfg.DATE_STRINGS || false
31+
};
32+
33+
if (srcCfg.SSL) {
34+
const sslConfig = {};
35+
36+
if (srcCfg.SSL.CUSTOM_CERT) {
37+
sslConfig.ca = srcCfg.SSL.CUSTOM_CERT;
38+
} else {
39+
sslConfig.rejectUnauthorized = srcCfg.SSL.hasOwnProperty('REJECT_UNAUTHORIZED') ? srcCfg.SSL.REJECT_UNAUTHORIZED : true;
40+
}
41+
42+
options.ssl = sslConfig;
43+
}
44+
45+
pools[poolName] = mysql.createPool(options);
46+
console.debug(`MySQL Adapter: Pool ${poolName} created`);
47+
return true;
48+
} else {
49+
console.error(`MySQL Adapter: Missing configuration for ${poolName}`);
50+
return false;
51+
}
52+
} catch (err) {
53+
console.error("MySQL Adapter: Error while closing connection", err);
54+
return false;
55+
}
56+
};
57+
58+
exports.connect = async (poolName) => {
59+
try {
60+
if (!pools[poolName]) {
61+
await this.createPool(poolName);
62+
}
63+
return pools[poolName];
64+
} catch (err) {
65+
console.error("MySQL Adapter: Error while retrieving a connection", err);
66+
throw new Error(err.message);
67+
}
68+
};
69+
70+
this.query = async (conn, query, params) => {
71+
return new Promise((resolve, reject) => {
72+
try {
73+
conn.query(query, params, (error, results) => {
74+
if (error) {
75+
console.error("MySQL Adapter: Failure in query: ", error);
76+
this.handleError(reject, error);
77+
} else {
78+
resolve(results);
79+
}
80+
});
81+
} catch (err) {
82+
console.error("MySQL Adapter: Failure in query: ", err);
83+
this.handleError(reject, err);
84+
}
85+
});
86+
};
87+
88+
this.handleError = (reject, error) => {
89+
const errorReturn = (config && config.HIDE_DB_ERRORS) ? new Error(genericError) : error;
90+
reject(errorReturn);
91+
};
92+
93+
exports.execute = async (srcName, query, params = {}) => {
94+
try {
95+
console.debug(query);
96+
if (params) {
97+
console.debug(JSON.stringify(params));
98+
}
99+
100+
const start = process.hrtime();
101+
const conn = await this.connect(srcName);
102+
103+
console.debug(
104+
`MySQL Adapter: Connection secured: ${process.hrtime(start)[0]}s ${
105+
process.hrtime(start)[1] / 1000000
106+
}ms`
107+
);
108+
const results = await this.query(conn, query, params);
109+
110+
console.debug(
111+
`MySQL Adapter: Query executed: ${process.hrtime(start)[0]}s ${
112+
process.hrtime(start)[1] / 1000000
113+
}ms`
114+
);
115+
116+
return results;
117+
} catch (err) {
118+
console.error("MySQL Adapter: Error while executing query", err);
119+
throw new Error(err.message);
120+
}
121+
};
122+
123+
exports.closeAllPools = async () => {
124+
try {
125+
for (const poolAlias of Object.keys(pools)) {
126+
await this.closePool(poolAlias);
127+
delete pools[poolAlias];
128+
console.debug(`MySQL Adapter: Pool ${poolAlias} closed`);
129+
}
130+
return true;
131+
} catch (err) {
132+
console.error("MySQL Adapter: Error while closing connection", err);
133+
return false;
134+
}
135+
};
136+
137+
exports.closePool = async (poolAlias) => {
138+
try {
139+
if (pools[poolAlias]) {
140+
const poolConn = pools[poolAlias];
141+
delete pools[poolAlias];
142+
await poolConn.end((err) => {
143+
if (err) {
144+
console.error(
145+
`Error while closing connection pool ${poolAlias}`,
146+
err
147+
);
148+
}
149+
});
150+
return true;
151+
} else {
152+
return true;
153+
}
154+
} catch (err) {
155+
console.error("MySQL Adapter: Error while closing connection", err);
156+
return false;
157+
}
158+
};

package.json

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "@softrams/nodejs-mysql-connector",
3+
"version": "0.0.13",
4+
"description": "Database connector wrapper to work with MySQL database from nodejs applications",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "yarn test"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/softrams/nodejs-mysql-connector.git"
12+
},
13+
"keywords": [
14+
"Nodejs",
15+
"MySQL",
16+
"Database"
17+
],
18+
"author": "Murali ([email protected])",
19+
"license": "UNLICENSED",
20+
"bugs": {
21+
"url": "https://github.com/softrams/nodejs-mysql-connector/issues"
22+
},
23+
"homepage": "https://github.com/softrams/nodejs-mysql-connector#readme",
24+
"dependencies": {
25+
"mysql": "^2.18.1"
26+
}
27+
}

0 commit comments

Comments
 (0)