Last active
March 28, 2022 12:32
-
-
Save jamesr2323/8952972abdb5c9c50c8fbeb4f7920548 to your computer and use it in GitHub Desktop.
Simple AWS Lambda Function to store a simple feed of text data in Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This was written to provide a simple serverless backend for a widget which displays live updating comments on a signup page. | |
The frontend can simple call $.post to add a comment, and $.get to retrieve the latest comments. | |
You need a Redis instance somewhere, you can get a free 30MB one from Redis Labs. | |
You'll also need to configure a AWS API Gateway endpoint which invokes this function for GET and POST requests | |
*/ | |
'use strict'; | |
const redis = require('redis'); // You'll need to upload Redis in node_modules. Easiest way to do this is do npm install redis --save in a blank directory, zip it and then upload to Lambda | |
exports.handler = (event, context, callback) => { | |
var redisClient = redis.createClient(process.env.REDIS_URL) | |
const done = (err, res) => callback(null, { | |
statusCode: err ? '400' : '200', | |
body: err ? err.message : JSON.stringify(res), | |
headers: { | |
'Content-Type': 'application/json', | |
"Access-Control-Allow-Origin" : "*" | |
}, | |
}); | |
const getComments = () => { | |
redisClient.lrange('comments', 0, 9, (err, reply) => { | |
done(null, {comments: reply}); | |
redisClient.quit(); | |
}); | |
} | |
const postComment = (body) => { | |
redisClient.lpush('comments', body.comment, (err, reply) => { | |
redisClient.ltrim('comments', 0, 49, (err, reply) => { | |
done(null, {}) | |
redisClient.quit() | |
}) | |
}); | |
} | |
switch (event.httpMethod) { | |
case 'GET': | |
getComments(); | |
break; | |
case 'POST': | |
postComment(JSON.parse(event.body)); | |
break; | |
default: | |
done(new Error(`Unsupported method "${event.httpMethod}"`)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment