Skip to content

Commit

Permalink
feat: remove middleware and expose getCurrentLambdaInvoke method
Browse files Browse the repository at this point in the history
  • Loading branch information
brettstack committed Apr 29, 2019
1 parent 7199aa5 commit b56c13b
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 150 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ When filing an issue, please check [existing open](https://github.com/awslabs/aw

Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:

1. You are working against the latest source on the *master* branch.
1. You are working against the latest source on the *develop* branch.
2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
3. You open an issue to discuss any significant work - we would hate for your time to be wasted.

Expand Down
25 changes: 13 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,29 @@ Want to get up and running quickly? [Check out our basic starter example](exampl
- [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model)/[CloudFormation](https://aws.amazon.com/cloudformation/aws-cloudformation-templates/) template
- Helper scripts to configure, deploy, and manage your application

### Getting the API Gateway event object
### Accessing the event and context objects

This package includes middleware to easily get the event object Lambda receives from API Gateway
This package exposes a function to easily get the `event` and `context` objects Lambda receives from the event source.

```js
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())
const { getCurrentLambdaInvoke } = require('aws-serverless-express')
app.get('/', (req, res) => {
res.json(req.lambda.event)
const currentLambdaInvoke = getCurrentLambdaInvoke()

res.json(currentLambdaInvoke.event)
})
```

## 4.0.0 Goals

1. Improved API - Simpler for end user to use and configure; extensible without breaking backwards compatibility or hurting API
1. Node.js 8+ only - can upgrade dependencies to latest (Jest); can use latest syntax in source and tests; can use server.listening; future-proof for Node.js 10
1. Promise resolution mode by default? Requires benchmarking. Otherwise try callback with callbackWaitsForEventLoop=false (configurable by user); requires benchmarking. If context.succeed is still most performant, leave as default.
1. Additional event sources - currently only supports API Gateway Proxy; should also support Lambda@Edge (https://github.com/awslabs/aws-serverless-express/issues/152) and ALB; have had a customer request for DynamoDB; should make it easy to provide your own IO mapping function.
1. Multiple header values - can get rid of set-cookie hack
1. Configure logging - NONE, ERROR, INFO, DEBUG; also include option to respond to 500s with the stack trace instead of empty string currently
1. Improved documentation
1. Option to strip base path for custom domains (https://github.com/awslabs/aws-serverless-express/issues/86)
2. Node.js 8+ only - can upgrade dependencies to latest (Jest); can use latest syntax in source and tests; can use server.listening; future-proof for Node.js 10
3. Promise resolution mode by default? Requires benchmarking. Otherwise try callback with callbackWaitsForEventLoop=false (configurable by user); requires benchmarking. If context.succeed is still most performant, leave as default.
4. Additional event sources - currently only supports API Gateway Proxy; should also support Lambda@Edge (https://github.com/awslabs/aws-serverless-express/issues/152) and ALB; have had a customer request for DynamoDB; should make it easy to provide your own IO mapping function.
5. Multiple header values - can get rid of set-cookie hack
6. Configure logging - NONE, ERROR, INFO, DEBUG; also include option to respond to 500s with the stack trace instead of empty string currently
7. Improved documentation
8. Option to strip base path for custom domains (https://github.com/awslabs/aws-serverless-express/issues/86)

### Is AWS serverless right for my app?

Expand Down
73 changes: 0 additions & 73 deletions __tests__/middleware.js

This file was deleted.

8 changes: 2 additions & 6 deletions __tests__/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ test('mapApiGatewayEventToHttpRequest: with headers', () => {
path: '/foo',
headers: {
'x-foo': 'foo',
'Content-Length': Buffer.byteLength('Hello serverless!'),
'x-lambda-event': encodeURIComponent(JSON.stringify(r.eventClone)),
'x-lambda-context': encodeURIComponent(JSON.stringify(r.context))
'Content-Length': Buffer.byteLength('Hello serverless!')
},
socketPath: '/tmp/server0.sock'
})
Expand All @@ -100,9 +98,7 @@ test('mapApiGatewayEventToHttpRequest: without headers', () => {
method: 'GET',
path: '/foo',
headers: {
'Content-Length': Buffer.byteLength('Hello serverless!'),
'x-lambda-event': encodeURIComponent(JSON.stringify(r.eventClone)),
'x-lambda-context': encodeURIComponent(JSON.stringify(r.context))
'Content-Length': Buffer.byteLength('Hello serverless!')
},
socketPath: '/tmp/server0.sock'
})
Expand Down
6 changes: 3 additions & 3 deletions examples/basic-starter/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const compression = require('compression')
const awsServerlessExpressMiddleware = require(process.env.NODE_ENV === 'test' ? '../../middleware' : 'aws-serverless-express/middleware')
const { getCurrentLambdaInvoke } = require(process.env.NODE_ENV === 'test' ? '../..' : 'aws-serverless-express')
const app = express()
const router = express.Router()

Expand All @@ -21,14 +21,14 @@ if (process.env.NODE_ENV === 'test') {
router.use(cors())
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({ extended: true }))
router.use(awsServerlessExpressMiddleware.eventContext())

// NOTE: tests can't find the views directory without this
app.set('views', path.join(__dirname, 'views'))

router.get('/', (req, res) => {
const currentLambdaInvoke = getCurrentLambdaInvoke()
res.render('index', {
apiUrl: req.lambda ? `https://${req.lambda.event.multiValueHeaders.Host}/${req.lambda.event.requestContext.stage}` : 'http://localhost:3000'
apiUrl: currentLambdaInvoke ? `https://${currentLambdaInvoke.event.multiValueHeaders.Host}/${currentLambdaInvoke.event.requestContext.stage}` : 'http://localhost:3000'
})
})

Expand Down
17 changes: 0 additions & 17 deletions middleware.js

This file was deleted.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"license": "Apache-2.0",
"files": [
"index.js",
"middleware.js",
"src/"
],
"main": "index.js",
Expand Down
34 changes: 19 additions & 15 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ const http = require('http')
const url = require('url')
const isType = require('type-is')

const currentLambdaInvoke = {}

function getCurrentLambdaInvoke () {
return currentLambdaInvoke
}

function setCurrentLambdaInvoke ({ event, context }) {
currentLambdaInvoke.event = event
currentLambdaInvoke.context = context
}

function getPathWithQueryStringParams ({ event }) {
return url.format({
pathname: event.path,
Expand All @@ -28,10 +39,6 @@ function getEventBody ({ event }) {
return Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')
}

function clone ({ object }) {
return JSON.parse(JSON.stringify(object))
}

function getContentType ({ contentTypeHeader }) {
// only compare mime type; ignore encoding part
return contentTypeHeader ? contentTypeHeader.split(';')[0] : ''
Expand All @@ -43,13 +50,9 @@ function isContentTypeBinaryMimeType ({ contentType, binaryMimeTypes }) {

function mapEventToHttpRequest ({
event,
eventWithoutBody = { ...clone({ object: event }), body: undefined },
context,
socketPath,
headers = {
...event.multiValueHeaders,
'x-lambda-event': encodeURIComponent(JSON.stringify(eventWithoutBody)),
'x-lambda-context': encodeURIComponent(JSON.stringify(context))
...event.multiValueHeaders
}
}) {
return {
Expand All @@ -64,8 +67,8 @@ function mapEventToHttpRequest ({
}
}

function mapApiGatewayEventToHttpRequest ({ event, context, socketPath }) {
const httpRequest = mapEventToHttpRequest({ event, context, socketPath })
function mapApiGatewayEventToHttpRequest ({ event, socketPath }) {
const httpRequest = mapEventToHttpRequest({ event, socketPath })

// NOTE: API Gateway is not setting Content-Length header on requests even when they have a body
if (event.body && !httpRequest.headers['Content-Length']) {
Expand All @@ -76,14 +79,14 @@ function mapApiGatewayEventToHttpRequest ({ event, context, socketPath }) {
return httpRequest
}

function mapAlbEventToHttpRequest ({ event, context, socketPath }) {
const httpRequest = mapEventToHttpRequest({ event, context, socketPath })
function mapAlbEventToHttpRequest ({ event, socketPath }) {
const httpRequest = mapEventToHttpRequest({ event, socketPath })

return httpRequest
}

function mapLambdaEdgeEventToHttpRequest ({ event, context, socketPath }) {
const httpRequest = mapEventToHttpRequest({ event, context, socketPath })
const httpRequest = mapEventToHttpRequest({ event, socketPath })

return httpRequest
}
Expand Down Expand Up @@ -190,10 +193,10 @@ function forwardRequestToNodeServer ({
eventSource,
eventFns = getEventFnsBasedOnEventSource({ eventSource })
}) {
setCurrentLambdaInvoke({ event, context })
try {
const requestOptions = eventFns.request({
event,
context,
socketPath: getSocketPath({ socketPathSuffix: server._socketPathSuffix })
})
const req = http.request(requestOptions, (response) => forwardResponse({ server, response, resolver, responseFn: eventFns.response }))
Expand Down Expand Up @@ -378,6 +381,7 @@ function configure ({
}

exports.configure = configure
exports.getCurrentLambdaInvoke = getCurrentLambdaInvoke

/* istanbul ignore else */
if (process.env.NODE_ENV === 'test') {
Expand Down
22 changes: 0 additions & 22 deletions src/middleware.js

This file was deleted.

0 comments on commit b56c13b

Please sign in to comment.