Skip to content

Commit 7b99653

Browse files
authored
Merge pull request #2 from vibhasfl/feature/adding-mysql-support
Feature/adding mysql support
2 parents 687585a + cfe1727 commit 7b99653

File tree

9 files changed

+65
-13
lines changed

9 files changed

+65
-13
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
# express-mongoose-es8-rest-api
22

33
## Description
4-
Nodejs boilerplate with express,Mongoose,ES8,Jwt to develop rest api
4+
Nodejs boilerplate with express,Mongoose,Mysql,ES8,Jwt to develop rest api
55

66
[![specification](https://img.shields.io/badge/ES8/ECMASCRIPT-2017-yellow.svg)](https://www.ecma-international.org/ecma-262/8.0/index.html)
77
![node version](https://img.shields.io/badge/node-%3E%3D%208.10.0-brightgreen.svg)
88
[![express](https://img.shields.io/badge/express-4.x-orange.svg)](https://github.com/expressjs/express)
99
[![mongoose](https://img.shields.io/badge/mongoose-5.4.12-red.svg)](https://mongoosejs.com/)
1010
[![jsonwebtoken](https://img.shields.io/badge/jsonwebtoken-8.4.0-green.svg)](https://github.com/auth0/node-jsonwebtoken)
11+
[![mysql](https://img.shields.io/badge/mysql-2.16-blue.svg)](https://github.com/mysqljs/mysql)
1112
[![code style](https://img.shields.io/badge/eslint--config--standard-%5E12.0.0-blue.svg)](https://github.com/standard/eslint-config-standard)
1213
![Dependencies](https://img.shields.io/badge/dependencies-up%20to%20date-brightgreen.svg)
1314

@@ -25,7 +26,7 @@ Nodejs boilerplate with express,Mongoose,ES8,Jwt to develop rest api
2526
- Manage enviroment via [dotenv](https://github.com/rolodato/dotenv-safe)
2627
- Code coverage with [istanbul](https://github.com/istanbuljs/nyc)
2728
- uses [helmet](https://github.com/helmetjs/helmet) to secure api endpoints which adds necessary security headers
28-
29+
- Added support for databases like [mysql](https://github.com/mysqljs/mysql) and [mongoDB](https://github.com/Automattic/mongoose) with async await
2930
## Getting Started
3031
1. Clone repository
3132
```

index.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
1+
import debug from 'debug'
12
require('dotenv').load()
3+
const log = debug('app')
24

3-
let unusedEnvVars = [ 'MONGO_HOSTNAME', 'MONGO_PORT', 'MONGO_DATABASE' ].filter((i) => !process.env[i])
4-
if (unusedEnvVars.length) throw new Error('Required ENV variables are not set: [' + unusedEnvVars.join(', ') + ']')
5+
let applicationEnvVars = [ 'APP_ENVIROMENT', 'PORT', 'USE_MONGODB', 'USE_MYSQL' ]
6+
let mysqlEnvVars = [ 'MYSQL_HOSTNAME', 'MYSQL_PORT', 'MYSQL_USERNAME', 'MYSQL_DATABASE', 'MYSQL_PASSWORD' ]
7+
let mongoEnvVars = [ 'MONGO_HOSTNAME', 'MONGO_PORT', 'MONGO_DATABASE' ]
8+
9+
if (process.env.USE_MONGODB) applicationEnvVars = [ ...applicationEnvVars, ...mongoEnvVars ]
10+
if (process.env.USE_MYSQL) applicationEnvVars = [ ...applicationEnvVars, ...mysqlEnvVars ]
11+
12+
let unusedEnvVars = applicationEnvVars.filter((i) => !process.env[i])
13+
14+
if (unusedEnvVars.length) {
15+
log('Required ENV variables are not set: [' + unusedEnvVars.join(', ') + ']')
16+
process.exit(1)
17+
}
518

619
const { app } = require('./server/app.js')
720

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"helmet": "^3.15.1",
1515
"joi": "^14.3.1",
1616
"jsonwebtoken": "^8.4.0",
17-
"mongoose": "^5.4.10"
17+
"mongoose": "^5.4.10",
18+
"mysql": "^2.16.0"
1819
},
1920
"devDependencies": {
2021
"@babel/cli": "^7.2.3",

server/app.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,22 @@ import helmet from 'helmet'
88
import { httpStatus } from './utils/httpStatus'
99
import { AppError } from './utils/appError'
1010
import { secretCallback } from './utils/secretCallback'
11+
import { connectMysql } from './config/mysqlconnect'
12+
1113
const app = express()
1214

1315
app.use(bodyParser.json())
1416
app.use(helmet())
15-
app.use(jwt({ secret: secretCallback }).unless({ path: [ '/api/health-check', '/api/users', '/api/auth/login' ], requestProperty: 'auth' }))
17+
app.use(jwt({ secret: secretCallback }).unless({ path: [ '/api/health-check', '/api/users', '/api/auth/login', '/api/users/testmysqlroute' ], requestProperty: 'auth' }))
1618
app.use('/api', Router)
1719

1820
// Handle 404
1921
app.use(function (req, res, next) {
2022
throw new AppError('Resource not found', httpStatus.NOT_FOUND)
2123
})
2224

23-
connectMongo()
25+
if (process.env.USE_MONGODB === 'true') connectMongo()
26+
if (process.env.USE_MYSQL === 'true') connectMysql()
2427

2528
app.use(errorHandler)
2629

server/config/errorHandler.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const log = debug('app')
88
// Note : calling next(err) will call this error handler if no other handler id defined.You can handle custom error over here
99

1010
const errorHandler = (err, req, res, next) => {
11-
log(err)
11+
log(err.toString())
1212

1313
if (err instanceof AppError) return res.status(err.status).json({ error: err.message, stack: process.env.APP_ENVIROMENT === 'dev' ? err.stack : undefined })
1414

server/config/mongoconnect.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@ const log = debug('app')
66
mongoose.Promise = Promise
77

88
mongoose.connection.on('connected', () => {
9-
log('Connection Established')
9+
log('MongoDB Connection Established')
1010
})
1111

1212
mongoose.connection.on('reconnected', () => {
13-
log('Connection Reestablished')
13+
log('MongoDB Connection Reestablished')
1414
})
1515

1616
mongoose.connection.on('disconnected', () => {
17-
log('Connection Disconnected')
17+
log('MongoDB Connection Disconnected')
1818
})
1919

2020
mongoose.connection.on('close', () => {
21-
log('Connection Closed')
21+
log('MongoDB Connection Closed')
2222
})
2323

2424
mongoose.connection.on('error', (error) => {
25-
log('ERROR: ' + error)
25+
log('MongoDB ERROR: ' + error)
2626
process.exit(1)
2727
})
2828

server/config/mysqlconnect.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import mysql from 'mysql'
2+
import debug from 'debug'
3+
import util from 'util'
4+
5+
const log = debug('app')
6+
// Note : You can remove mysqldetaillog and use log instead
7+
const mysqldetaillog = debug('mysqldetaillog')
8+
9+
const pool = mysql.createPool({ host: process.env.MYSQL_HOSTNAME, user: process.env.MYSQL_USERNAME, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE })
10+
11+
pool.on('connection', (connection) => mysqldetaillog(`Mysql Connection #${connection.threadId} created`))
12+
pool.on('acquire', (connection) => mysqldetaillog(`Mysql Connection #${connection.threadId} acquired`))
13+
pool.on('release', (connection) => mysqldetaillog(`Mysql Connection #${connection.threadId} released`))
14+
15+
pool.query = util.promisify(pool.query)
16+
17+
export const connectMysql = () => {
18+
pool.getConnection(function (err, connection) {
19+
if (err) {
20+
log(`Mysql ${err.toString()}`)
21+
process.exit(1)
22+
}
23+
log(`Mysql connection established`)
24+
connection.release()
25+
})
26+
}
27+
28+
export { pool }

server/modules/users/user.routes.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@ const userRoutes = express.Router()
99
userRoutes.get('/', asyncWrapper(users.index))
1010
userRoutes.post('/', validate(newuser), asyncWrapper(users.create))
1111
userRoutes.put('/:id', asyncWrapper(users.update))
12+
userRoutes.get('/testmysqlroute', asyncWrapper(users.testMysql))
1213

1314
export { userRoutes }

server/modules/users/users.controller.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { userModel } from './user.model'
22
import { httpStatus } from '../../utils/httpStatus'
3+
import { pool } from '../../config/mysqlconnect'
34
const users = {}
45

56
users.index = async (req, res) => {
@@ -21,4 +22,8 @@ users.update = async (req, res) => {
2122
return res.json({ message: 'Record updated' })
2223
}
2324

25+
users.testMysql = async (req, res) => {
26+
let data = await pool.query('Select * from users')
27+
return res.json({ data })
28+
}
2429
export { users }

0 commit comments

Comments
 (0)