Skip to content

Instantly share code, notes, and snippets.

@redgeoff
Last active July 27, 2021 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redgeoff/f1393eaa75ecb8e39b4759a84b0e6f5b to your computer and use it in GitHub Desktop.
Save redgeoff/f1393eaa75ecb8e39b4759a84b0e6f5b to your computer and use it in GitHub Desktop.
Basic Lambda to serve POST request
import express from 'express';
import cors from 'cors';
import handler from './lambda';
import lambdaToExpress from './lambda-to-express';
const PORT = 3000;
const app = express();
app.use(cors());
app.use(express.json()); // Parse JSON bodies
app.put('/lead/:leadId', lambdaToExpress(handler));
app.listen(PORT);
// Convert from a Lambda to an ExpressJS handler
const lambdaToExpress = async (handler) => {
return async (req, res) => {
// Repackage the express parameters as an event object for the Lambda
const event = {
body: JSON.stringify(req.body),
headers: req.headers,
queryStringParameters: req.query,
pathParameters: req.params
};
const handlerRes = await handler(event);
// Instruct express to use the response from the Lambda
res.status(handlerRes.statusCode).json(JSON.parse(handlerRes.body))
};
}
export default lambdaToExpress;
import leadService from './lead-service';
// Define a handler for `PUT /lead/:leadId` that accepts the request body payload `{ name, email }`
const handler = async (event) => {
// Parse the request parameters
const { name, email } = JSON.parse(event.body);
const { leadId } = event.pathParameters;
// Assume this is the service-layer code that actually performs the updating of the lead
await leadService.update(leadId, name, email);
// Return a 200 success code and the full lead
return {
statusCode: 200,
body: JSON.stringify({
id: leadId,
name,
email
})
};
}
export default handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment