I’d pick option 2. You’d need your Lambda function to log into Realm (using anonymous authentication if you prefer) – I’d suggest doing that outside of the handler so that you aren’t logging in every time that the function runs. Here’s a completely unrelated Lambda function that I’ve written – but it does does show how to do some pre-work outside of the handler:
const {WebClient} = require('@slack/web-api');
const AWS = require('aws-sdk');
// This work is done outside of the handler so that it's only run when the
// function is instantiated, not on every execution
const secretName = process.env.secretName;
let slackToken = "";
let channelId = "";
let secretsManager = new AWS.SecretsManager();
const initPromise = new Promise((resolve, reject) => {
secretsManager.getSecretValue(
{ SecretId: secretName },
function(err, data) {
if(err) {
console.error(`Failed to fetch secrets: ${err}`);
reject();
} else {
const secrets = JSON.parse(data.SecretString);
slackToken = secrets.slackToken;
channelId = secrets.channelId;
resolve()
}
}
)
});
exports.handler = async (event) => {
await initPromise;
const client = new WebClient({ token: slackToken });
const blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `*${event.detail.fullDocument.author} said...*\n\n${event.detail.fullDocument.text}`
},
"accessory": {
"type": "image",
"image_url": "https://stitch-statichosting-prod.s3.amazonaws.com/5fd9ede61919a2df04497366/RChat%20Icon%20-%20180.png",
// "image_url": "https://cdn.dribbble.com/users/27903/screenshots/4327112/69chat.png?compress=1&resize=800x600",
"alt_text": "Chat logo"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `Sent from <https://github.com/ClusterDB/RChat|RChat>`
}
},
{
"type": "divider"
}
]
await publishMessage(
channelId, `Sent from RChat: ${event.detail.fullDocument.author} said "${event.detail.fullDocument.text}"`,
blocks);
const response = {
statusCode: 200,
body: JSON.stringify('Slack message sent')
};
return response;
async function publishMessage(id, text, blocks) {
try {
const result = await client.chat.postMessage({
token: slackToken,
channel: id,
text: text,
blocks: blocks
});
}
catch (error) {
console.error(error);
}
}
};