forked from willfarrell/middy-rds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (48 loc) · 1.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const tls = require('tls')
const { promisify } = require('util')
const { getInternal, processCache, clearCache } = require('@middy/util')
const ssl = require('./ssl')
const defaults = {
client: undefined,
config: {},
internalData: {},
cacheKey: 'rds',
cachePasswordKey: 'rds',
cacheExpiry: -1
}
const defaultConnection = { ssl }
const rdsMiddleware = (opts = {}) => {
const options = Object.assign({}, defaults, opts)
if (!options.client) throw new Error('client option missing')
const fetch = async (request) => {
const values = await getInternal(options.internalData, request)
options.config.connection = Object.assign({}, defaultConnection, options.config.connection, values)
const db = options.client(options.config)
db.raw('SELECT 1') // don't await, used to force open connection
.catch(e => {
// Connection failed for some reason
// log and clear cache, force re-connect
console.error('middy-rds SELECT 1', e.message)
clearCache([options.cachePasswordKey])
clearCache([options.cacheKey])
})
// cache the connection, not the credentials as they may change over time
return db
}
const rdsMiddlewareBefore = async (request) => {
const {value} = processCache(options, fetch, request)
Object.assign(request.context, { db: await value }) // await due to fetch being a promise
}
const rdsMiddlewareAfter = async (request) => {
if (options.cacheExpiry === 0) {
await request.context.db.destroy()
}
}
const rdsMiddlewareOnError = rdsMiddlewareAfter
return {
before: rdsMiddlewareBefore,
after: rdsMiddlewareAfter,
onError: rdsMiddlewareOnError
}
}
module.exports = rdsMiddleware