From f99dcb19d8b89f24799b46ae8d27a38662e7c118 Mon Sep 17 00:00:00 2001 From: Tommy Brunn Date: Wed, 9 Sep 2020 18:10:17 +0200 Subject: [PATCH] Add `createHandler` method for programmatic configuration --- README.md | 17 +++++++++++++++++ index.js | 54 ++++++++++++++++++++++++++++++------------------------ 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 4d26ee4..38b3664 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,23 @@ The final step is to deploy the integration to AWS Lambda: npm install npm run deploy +## Programmatic usage + +If you want to programmatically pass in a configuration, rather than relying on +environment variables, you can create your own handler: + +```js +const { createHandler, config } = require('lambda-cloudwatch-slack'); + +exports.handler = createHandler({ + ...config, + unencryptedHookUrl: 'https://hooks.slack.com/services/...' +}) +``` + +This can for example be useful if you need to get the webhook url from +AWS Parameter Store or Secrets Manager at runtime. + ## Tests With the variables filled in, you can test the function: diff --git a/index.js b/index.js index c61ab4e..904aef0 100644 --- a/index.js +++ b/index.js @@ -410,27 +410,33 @@ var processEvent = function(event, context) { }); }; -exports.handler = function(event, context) { - if (hookUrl) { - processEvent(event, context); - } else if (config.unencryptedHookUrl) { - hookUrl = config.unencryptedHookUrl; - processEvent(event, context); - } else if (config.kmsEncryptedHookUrl && config.kmsEncryptedHookUrl !== '') { - var encryptedBuf = new Buffer(config.kmsEncryptedHookUrl, 'base64'); - var cipherText = { CiphertextBlob: encryptedBuf }; - var kms = new AWS.KMS(); - - kms.decrypt(cipherText, function(err, data) { - if (err) { - console.log("decrypt error: " + err); - processEvent(event, context); - } else { - hookUrl = "https://" + data.Plaintext.toString('ascii'); - processEvent(event, context); - } - }); - } else { - context.fail('hook url has not been set.'); - } -}; +exports.config = config + +exports.createHandler = function (config) { + return function (event, context) { + if (hookUrl) { + processEvent(event, context); + } else if (config.unencryptedHookUrl) { + hookUrl = config.unencryptedHookUrl; + processEvent(event, context); + } else if (config.kmsEncryptedHookUrl && config.kmsEncryptedHookUrl !== '') { + var encryptedBuf = new Buffer(config.kmsEncryptedHookUrl, 'base64'); + var cipherText = { CiphertextBlob: encryptedBuf }; + var kms = new AWS.KMS(); + + kms.decrypt(cipherText, function (err, data) { + if (err) { + console.log("decrypt error: " + err); + processEvent(event, context); + } else { + hookUrl = "https://" + data.Plaintext.toString('ascii'); + processEvent(event, context); + } + }); + } else { + context.fail('hook url has not been set.'); + } + }; +} + +exports.handler = exports.createHandler(config) \ No newline at end of file