Skip to content

Commit db1805b

Browse files
committed
Advanced example [ci skip]
1 parent cec8a29 commit db1805b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,51 @@ module.exports = { handler }
4141
```
4242

4343
If the above file in your Lambda source was called `index.js` then the name of the handler in the Lambda configuration is `index.handler`
44+
45+
### Advanced example
46+
47+
Sometimes the application needs to read configuration from remote source before it can start processing requests. For example it may need to decrypt some secrets managed by KMS.
48+
49+
```javascript
50+
const lambdaRequestHandler = require('lambda-request-handler')
51+
const AWS = require('aws-sdk')
52+
const express = require('express')
53+
54+
const kms = new AWS.KMS()
55+
56+
const myKmsPromise = () =>
57+
kms.decrypt({
58+
CiphertextBlob: Buffer.from(process.env.ENCRYPTED_SECRET, 'base64')
59+
})
60+
.promise()
61+
.then((data) => {
62+
process.env.SECRET = data.Plaintext.toString('ascii')
63+
});
64+
65+
cont app = express()
66+
67+
app.get('/secret', (req, res) => {
68+
res.json({
69+
secret: process.env.SECRET,
70+
})
71+
})
72+
73+
const myAppHandler = lambdaRequestHandler(app)
74+
75+
let _myKmsPromise;
76+
77+
const handler = (event) => {
78+
if (!_myKmsPromise) {
79+
// _myKmsPromise is in global scope so that only one request to KMS is made during this Lambda lifecycle
80+
_myKmsPromise = myKmsPromise();
81+
}
82+
return _myKmsPromise
83+
.then(() => {
84+
// at this point the secret is decrypted and available as process.env.SECRET to the app
85+
return myAppHandler(event);
86+
})
87+
}
88+
89+
module.exports = { handler }
90+
91+
```

0 commit comments

Comments
 (0)