Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active Aug 30, 2022
Embed
What would you like to do?
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

ShanonJackson commented Aug 30, 2022

@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