Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

aws-serverless-express

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aws-serverless-express - npm Package Compare versions

Comparing version 2.2.0 to 3.0.0

87

index.js

@@ -24,2 +24,11 @@ /*

function getContentType(params) {
// only compare mime type; ignore encoding part
return params.contentTypeHeader ? params.contentTypeHeader.split(';')[0] : ''
}
function isContentTypeBinaryMimeType(params) {
return params.binaryMimeTypes.indexOf(params.contentType) !== -1
}
function mapApiGatewayEventToHttpRequest(event, context, socketPath) {

@@ -30,4 +39,4 @@ const headers = event.headers || {} // NOTE: Mutating event.headers; prefer deep clone of event.headers

headers['x-apigateway-event'] = JSON.stringify(eventWithoutBody)
headers['x-apigateway-context'] = JSON.stringify(context)
headers['x-apigateway-event'] = encodeURIComponent(JSON.stringify(eventWithoutBody))
headers['x-apigateway-context'] = encodeURIComponent(JSON.stringify(context))

@@ -52,3 +61,3 @@ return {

.on('end', () => {
let body = Buffer.concat(buf)
const bodyBuffer = Buffer.concat(buf)
const statusCode = response.statusCode

@@ -76,14 +85,5 @@ const headers = response.headers

// only compare mime type; ignore encoding part
const contentType = headers['content-type'] ? headers['content-type'].split(';')[0] : ''
let isBase64Encoded
if (server._binaryTypes.indexOf(contentType) !== -1) {
body = body.toString('base64')
isBase64Encoded = true
} else {
body = body.toString('utf8')
isBase64Encoded = false
}
const contentType = getContentType({ contentTypeHeader: headers['content-type'] })
const isBase64Encoded = isContentTypeBinaryMimeType({ contentType, binaryMimeTypes: server._binaryTypes })
const body = bodyBuffer.toString(isBase64Encoded ? 'base64' : 'utf8')
const successResponse = {statusCode, body, headers, isBase64Encoded}

@@ -96,2 +96,3 @@

function forwardConnectionErrorResponseToApiGateway(server, error, context) {
console.log('ERROR: aws-serverless-express connection error')
console.error(error)

@@ -108,2 +109,3 @@ const errorResponse = {

function forwardLibraryErrorResponseToApiGateway(server, error, context) {
console.log('ERROR: aws-serverless-express error')
console.error(error)

@@ -120,11 +122,19 @@ const errorResponse = {

function forwardRequestToNodeServer(server, event, context) {
const requestOptions = mapApiGatewayEventToHttpRequest(event, context, getSocketPath(server._socketPathSuffix))
const req = http.request(requestOptions, (response) => forwardResponseToApiGateway(server, response, context))
try {
const requestOptions = mapApiGatewayEventToHttpRequest(event, context, getSocketPath(server._socketPathSuffix))
const req = http.request(requestOptions, (response, body) => forwardResponseToApiGateway(server, response, context))
if (event.body) {
if (event.isBase64Encoded) {
event.body = new Buffer(event.body, 'base64')
}
if (event.body) {
req.write(event.body)
}
req.write(event.body)
}
req.on('error', (error) => forwardConnectionErrorResponseToApiGateway(server, error, context))
.end()
req.on('error', (error) => forwardConnectionErrorResponseToApiGateway(server, error, context))
.end()
} catch (error) {
forwardLibraryErrorResponseToApiGateway(server, error, context)
return server
}
}

@@ -140,3 +150,3 @@

exports.createServer = (requestListener, serverListenCallback, binaryTypes) => {
function createServer (requestListener, serverListenCallback, binaryTypes) {
const server = http.createServer(requestListener)

@@ -158,4 +168,7 @@

++server._socketPathSuffix
server.close(() => startServer(server))
return server.close(() => startServer(server))
}
console.log('ERROR: server error')
console.error(error)
})

@@ -166,21 +179,15 @@

exports.proxy = (server, event, context) => {
try {
if (server._isListening) {
forwardRequestToNodeServer(server, event, context)
} else {
startServer(server)
.on('listening', () => {
try {
forwardRequestToNodeServer(server, event, context)
} catch(error) {
forwardLibraryErrorResponseToApiGateway(server, error, context)
}
})
}
} catch (error) {
forwardLibraryErrorResponseToApiGateway(server, error, context)
function proxy(server, event, context) {
if (server._isListening) {
forwardRequestToNodeServer(server, event, context)
return server
} else {
return startServer(server)
.on('listening', () => proxy(server, event, context))
}
}
exports.createServer = createServer
exports.proxy = proxy
if (process.env.NODE_ENV === 'test') {

@@ -187,0 +194,0 @@ exports.getPathWithQueryStringParams = getPathWithQueryStringParams

@@ -13,4 +13,4 @@ module.exports.eventContext = options => (req, res, next) => {

req[reqPropKey] = {
event: JSON.parse(req.headers['x-apigateway-event']),
context: JSON.parse(req.headers['x-apigateway-context'])
event: JSON.parse(decodeURIComponent(req.headers['x-apigateway-event'])),
context: JSON.parse(decodeURIComponent(req.headers['x-apigateway-context']))
}

@@ -17,0 +17,0 @@

{
"name": "aws-serverless-express",
"version": "2.2.0",
"version": "3.0.0",
"description": "This library enables you to utilize AWS Lambda and Amazon API Gateway to respond to web and API requests using your existing Node.js application framework.",

@@ -5,0 +5,0 @@ "keywords": [

@@ -21,35 +21,12 @@ Run serverless applications and REST APIs using your existing [Node.js](https://nodejs.org/) application framework, on top of [AWS Lambda](https://aws.amazon.com/lambda/) and [Amazon API Gateway](https://aws.amazon.com/api-gateway/). The sample provided allows you to easily build serverless web applications/services and RESTful APIs using the [Express](https://expressjs.com/) framework.

## Example
## Quick Start/Example
In addition to a basic Lambda function and Express server, the `example` directory includes a [Swagger file](http://swagger.io/specification/), [CloudFormation template](https://aws.amazon.com/cloudformation/aws-cloudformation-templates/) with [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model), and helper scripts to help you set up and manage your application.
Want to get up and running quickly? [Check out our example](example/README.md) which includes:
### Steps for running the example
This guide assumes you have already [set up an AWS account](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/AboutAWSAccounts.html) and have the latest version of the [AWS CLI](https://aws.amazon.com/cli/) installed.
- Lambda function
- Express server
[Swagger file](http://swagger.io/specification/)
- [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
1. From your preferred project directory: `git clone https://github.com/awslabs/aws-serverless-express.git && cd aws-serverless-express/example`.
2. Run `npm run config -- --account-id="<accountId>" --bucket-name="<bucketName>" [--region="<region>" --function-name="<functionName>"]` to configure the example, eg. `npm run config -- --account-id="123456789012" --bucket-name="my-bucket" --region="us-west-2" --function-name="my-function"`. This modifies `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` with your account ID, bucket, region and function name (region defaults to `us-east-1` and function name defaults to `AwsServerlessExpressFunction`). If the bucket you specify does not yet exist, the next step will create it for you. This step modifies the existing files in-place; if you wish to make changes to these settings, you will need to modify `package.json`, `simple-proxy-api.yaml` and `cloudformation.yaml` manually.
3. Run `npm run setup` (Windows users: `npm run win-setup`) - this installs the node dependencies, creates an S3 bucket (if it does not already exist), packages and deploys your serverless Express application to AWS Lambda, and creates an API Gateway proxy API.
4. After the setup command completes, open the AWS CloudFormation console https://console.aws.amazon.com/cloudformation/home and switch to the region you specified. Select the `AwsServerlessExpressStack` stack, then click the `ApiUrl` value under the __Outputs__ section - this will open a new page with your running API. The API index lists the resources available in the example Express server (`app.js`), along with example `curl` commands.
See the sections below for details on how to migrate an existing (or create a new) Node.js project based on this example. If you would prefer to delete AWS assets that were just created, simply run `npm run delete-stack` to delete the CloudFormation Stack, including the API and Lambda Function. If you specified a new bucket in the `config` command for step 1 and want to delete that bucket, run `npm run delete-bucket`.
### Creating or migrating a Node.js project based on the example
To use this example as a base for a new Node.js project:
1. Copy the files in the `example` directory into a new project directory (`cp -r ./example ~/projects/my-new-node-project`). If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (you may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
2. After making updates to `app.js`, simply run `npm run package-deploy` (Windows users: `npm run win-package-deploy`).
To migrate an existing Node server:
1. Copy the following files from the `example` directory: `api-gateway-event.json`, `cloudformation.yaml`, `lambda.js`, and `simple-proxy-api.yaml`. Additionally, copy the `scripts` and `config` sections of `example/package.json` into your existing `package.json` - this includes many helpful commands to manage your AWS serverless assets and perform _basic_ local simulation of API Gateway and Lambda. If you have not already done so, follow the [steps for running the example](#steps-for-running-the-example) (be sure to copy over `scripts/configure.js`. You may want to first modify some of the resource names to something more project-specific, eg. the CloudFormation stack, Lambda function, and API Gateway API).
2. From your existing project directory, run `npm install --save aws-serverless-express`.
3. Modify `lambda.js` to import your own server configuration (eg. change `require('./app')` to `require('./server')`). You will need to ensure you export your app configuration from the necessary file (eg. `module.exports = app`). This library takes your app configuration and listens on a Unix Domain Socket for you, so you can remove your call to `app.listen()` (if you have a `server.listen` callback, you can provide it as the second parameter in the `awsServerlessExpress.createServer` method).
4. Modify the `CodeUri` property of the Lambda function resource in `cloudformation.yaml` to point to your application directory (e.g. `CodeUri: ./src`). If you are using a build tool (e.g. Gulp, Grunt, Webpack, Rollup, etc.), you will instead want to point to your build output directory.
5. Run `npm run package-deploy` (Windows users: `npm run win-package-deploy`) to package and deploy your application.
To perform a basic, local simulation of API Gateway and Lambda with your Node server, update `api-gateway-event.json` with some values that are valid for your server (`httpMethod`, `path`, `body` etc.) and run `npm run local`. AWS Lambda uses NodeJS 4.3 LTS, and it is recommended to use the same version for testing purposes.
If you need to make modifications to your API Gateway API, modify `simple-proxy-api.yaml` and run `npm run package-deploy`. If your API requires CORS, be sure to modify the two `options` methods defined in the Swagger file, otherwise you can safely remove them. To modify your other AWS assets, make your changes to `cloudformation.yaml` and run `npm run package-deploy`. Alternatively, you can manage these assets via the AWS console.
### Getting the API Gateway event object

@@ -61,2 +38,5 @@ This package includes middleware to easily get the event object Lambda receives from API Gateway

app.use(awsServerlessExpressMiddleware.eventContext())
app.get('/', (req, res) => {
res.json(req.apiGateway.event)
})
```

@@ -77,10 +57,10 @@

- [API Monitoring](http://docs.aws.amazon.com/apigateway/latest/developerguide/monitoring-cloudwatch.html)
- [Request Validation](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)
- [Documentation](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-documenting-api.html)
#### Cons
- Currently limited to Node.js 4.3 (LTS)
- For apps that may not see traffic for several minutes at a time, you could see [cold starts](https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/)
- May be more expensive for high-traffic apps
- Cannot use native libraries (aka [Addons](https://nodejs.org/api/addons.html)) unless you package your app on an EC2 machine running Amazon Linux
- Stateless only
- API Gateway has a timeout of 30 seconds, and Lambda has a maximum execution time of 5 minutes.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc