Last active
July 27, 2021 14:48
-
-
Save redgeoff/f1393eaa75ecb8e39b4759a84b0e6f5b to your computer and use it in GitHub Desktop.
Basic Lambda to serve POST request
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
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); |
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
// 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; |
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
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, | |
}) | |
}; | |
} | |
export default handler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment