Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active August 30, 2022 09:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/f87448d2c1c13d467f3ea8fc7e864955 to your computer and use it in GitHub Desktop.
Save Sleavely/f87448d2c1c13d467f3ea8fc7e864955 to your computer and use it in GitHub Desktop.
A helper for running a local webserver against lambda-api
// Require the framework and instantiate it
const api = require('lambda-api')()
// Define a route
api.get('/status', async (req, res) => {
return { status: 'ok' }
})
api.get('/README.md', async (req, res) => {
res.sendFile('./README.md')
})
module.exports = api
const api = require('./api')
// Declare your Lambda handler
exports.handler = async (event, context) => {
// Run the request
return api.run(event, context)
}
/**
* A minimal web server that converts the request
* object to something the lambda-api module understands.
*/
const api = require('./api')
const http = require('http')
const serverWrapper = http.createServer(function (request, response) {
const url = new URL(request.url, `http://${request.headers.host}/`)
// The event object we're faking is a lightweight based on:
// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-api-gateway-request
const event = {
httpMethod: request.method.toUpperCase(),
path: url.pathname,
resource: '/{proxy+}',
queryStringParameters: [...url.searchParams.keys()].reduce((output, key) => { output[key] = url.searchParams.get(key); return output }, {}),
headers: request.headers,
requestContext: {},
pathParameters: {},
stageVariables: {},
isBase64Encoded: false,
body: request.body,
}
api.run(event, {})
.then((res) => {
let {
body,
headers,
statusCode,
} = res
if (res.isBase64Encoded) {
body = Buffer.from(body, 'base64')
}
if (!headers['content-length'] && body) {
headers['content-length'] = body.length
}
response.writeHead(statusCode, headers)
response.end(body)
})
.catch((err) => {
console.error('Something went horribly, horribly wrong')
console.error(err)
response.writeHead(500, { 'content-length': 0 })
response.end('')
})
})
serverWrapper.listen(process.env.PORT || 3000, () => {
console.log(`Listening on http://localhost:${serverWrapper.address().port}/`)
})
@ShanonJackson
Copy link

@Sleavely

You should take a look at this, if you're interested in running Lambda locally https://docs.sst.dev (AWS-CDK )

Basically is feature complete lambda on your local environment, and not using emulation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment