An AWS Lambda function that serves as a MongoDB connection proxy.
It uses MongoDB native driver, Lambda & Secrets Manager.
With MongoDB Lambda Proxy, your Lambda functions don't need to establish its own database connection. Instead, they will invoke "Proxy", sending the query parameters. Once invoked, the Proxy will run the query using the standard MongoDB Node.js driver, and reply back with the query results.
This will help you to reduce database stress, idle connections, etc. It has support for find, update, delete, aggregate, etc.
See webiny's blog to understand more about the problem that Proxy solves.
Please note the current implementation serializes and de-serializes
JSON objects. This causes Dates and other types to be tranformed to
strings and others.
const dbQuery = {
collection: 'users',
op: 'findOne',
query: {
name: 'Jon'
},
options: {
fields: { email: 1 },
}
}
return new Promise((resolve, reject) => {
var params = {
FunctionName: 'myDbProxyFunctionName',
InvocationType: 'RequestResponse',
LogType: 'None',
Payload: JSON.stringify(dbQuery)
}
lambda.invoke(params, (err, result) => {
if (err) return reject(err)
const response = JSON.parse(result.Payload)
if (!response.success) return reject({
reason: response.reason,
error: response.error
})
return resolve(response.result)
})
})
// Example outputs:
//
// Resolves: { email: 'jon@example.com' }
// Resolves: [ { email: 'jon@example.com' } ]
// Rejects: { reason: 'Unrecognized pipeline stage name: \'$matcsh\'', error: '......' }
// Rejects: { reason: 'failed to connect to server...', error: '......' }
- Create an AWS Secret with the database connection details (see below).
- Create the Lambda function. Specify an environment variable
SECRET_MONGODB_CONNECTIONDETAILS
with the name of the secret you have previously created. - Make sure that your Lambda function have access to Secret Manager. (IAM)
SECRET_MONGODB_CONNECTIONDETAILS
required name of the secret where the connection details are stored.MONGODB_POOLSIZE
optional size of connection pool. Defaults to 5
For improved security, you must specify the connection details via a AWS Secret, with the following format:
{
"username": "jon",
"password": "snow",
"hostname": "localhost",
"database": "testing",
"query": "retryWrites=true&w=majority"
}