From 3a429e7483e96041e1aa71ec23365a3f48cc09e2 Mon Sep 17 00:00:00 2001 From: Luciano Pellacani Franca Date: Tue, 14 Feb 2017 18:14:04 +0000 Subject: [PATCH] updating README - adding support for Lambda --- README.md | 57 ++++++++ app/routes/user.js | 3 +- aws-serverless-express/LICENSE | 201 +++++++++++++++++++++++++++ aws-serverless-express/README.md | 87 ++++++++++++ aws-serverless-express/index.js | 185 ++++++++++++++++++++++++ aws-serverless-express/middleware.js | 23 +++ aws-serverless-express/package.json | 62 +++++++++ claudia.json | 6 +- lambda.js | 4 +- package.json | 2 +- test.js | 0 11 files changed, 623 insertions(+), 7 deletions(-) create mode 100644 aws-serverless-express/LICENSE create mode 100644 aws-serverless-express/README.md create mode 100644 aws-serverless-express/index.js create mode 100644 aws-serverless-express/middleware.js create mode 100644 aws-serverless-express/package.json create mode 100644 test.js diff --git a/README.md b/README.md index 70d8a8a..5e8f3fa 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,60 @@ # S.A.P.O +## Instalação + +Configurações: + +keys.js: contém chaves e informações referentes as conexões com o banco e chave para criptografia das sessões dos usuários. +settings.json: contém uma flag para difinir se o banco será ou não populado novamente com os dados padrões do sistema. + +### Local + +1- `git clone https://github.com/TCEES-NTI/SAPO-API.git` +2- `cd ` +3- `npm install` +4- `npm start` - Para testes locais. + +### Zeit NOW + +[Zeit NOW](https://zeit.co/now) é um serviço de hospedagem gratuito de serviços NodeJS de maneira simplificada. Fazer deploy nessa solução é simplíssimo só existe o +problema do plano gratuito ter o código aberto apenas adicionando /_src ao final da URL. + +1- `npm i -g now` +2- `git clone https://github.com/TCEES-NTI/SAPO-API.git` +3- `cd ` +4- `npm install` +5- `now` - Será pedido um email e a ativação da conta por este email, posteriormente a isso será lhe dado o endereço da nova API. + +### AWS Lambda + +É possível fazer o deploy da solução na Amazon utilizando também funções lambda (Serviço ofertado pela AWS). Fazer o deploy da API utilizando essa solução tem como +vantagens a alta escalabilidade e o baixo custo para manutenção da mesma. + +Observações: +1- É necessário ter uma conta na AWS ativa. (É seguro.. eu garanto!) +2- A função responsável pela nossa API deve ter: +2.1- No mínimo 256mb de RAM para funcionar sem travar. +2.2- Ao menos 512mb de RAM para funcionar razoavelmente bem. +2.3- 20 segundos de timeout para garantia dos endpoints mais complexos. +3- O guia de instalação apresentado é referente a uma maquina rodando Ubuntu, caso esteja utilizando outro SO por favor procure os comandos no respectivo sistema. +4- Considera-se que o usuário tem instalado NodeJS na maquina de instalação. + +Fazendo deploy da API usando AWS Lambda functions: +1- `export AWS_ACCESS_KEY_ID=` +2- `export AWS_SECRET_ACCESS_KEY=` +3- `cd ` +4- `npm install` +5- `npm start` - Para testes locais. +6- `npm run create-deploy` - Após o termino dessa etapa irá aparecer no console o endereço da sua API recém deployada. +7- Navegar no [painel da AWS](https://console.aws.amazon.com). +8- Entrar no painel gerencial das funções Lambda e escolher a função recém implementada. +9- Selecionar a aba Configuration e em seguida clicar em "Advanced Settings" +10- Alterar os valores de memória e timeout conforme suas necessidades (Atenção ao item 2 das observações.) + +## Uso + +## API + +## Contribuições + [![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) diff --git a/app/routes/user.js b/app/routes/user.js index da1b7eb..92d0072 100644 --- a/app/routes/user.js +++ b/app/routes/user.js @@ -37,10 +37,11 @@ module.exports = (router, JWTAuth) => { if (err || !isMatch) { res.status(403).send('Wrong password for the provided user.') } + let token = jwt.sign(user, config.SECRET, { expiresIn: EXPIRESIN }) res.json({ success: true, message: 'Enjoy your token!', - token: jwt.sign(user, config.SECRET, { expiresIn: EXPIRESIN }) + token: token }) next() }) diff --git a/aws-serverless-express/LICENSE b/aws-serverless-express/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/aws-serverless-express/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/aws-serverless-express/README.md b/aws-serverless-express/README.md new file mode 100644 index 0000000..6e59d51 --- /dev/null +++ b/aws-serverless-express/README.md @@ -0,0 +1,87 @@ +This library enables you to utilize [AWS Lambda](https://aws.amazon.com/lambda/) and [Amazon API Gateway](https://aws.amazon.com/api-gateway/) to respond to web and API requests using your existing [Node.js](https://nodejs.org/) application framework. The sample provided allows you to easily build serverless web applications/services and RESTful APIs using the [Express](https://expressjs.com/) framework. + +## Getting Started + +```bash +npm install aws-serverless-express +``` + +```js +// lambda.js +'use strict' +const awsServerlessExpress = require('aws-serverless-express') +const app = require('./app') +const server = awsServerlessExpress.createServer(app) + +exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context) +``` + +[Package and create your Lambda function](http://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html), then configure a simple proxy API using Amazon API Gateway and integrate it with your Lambda function. + +## 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/), and helper scripts to help you set up and manage your AWS assets. + +### Windows support +Windows users must have 7-Zip CLI installed http://www.7-zip.org/download.html and added to their path (`setx path "%path%;C:\Program Files\7-Zip"`) to run the commands. You must also use the `win-` prefixed commands, eg. `npm run win-setup`. If you do not want to install 7-Zip, you can instead zip the necessary files using the Windows UI and modify the commands accordingly. + +### 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 [AWS CLI](https://aws.amazon.com/cli/) installed. + +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="" --bucket-name="" [--region="" --function-name=""]` 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.json` 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.json` manually. +3. Run `npm run setup` (Windows users: `npm run win-setup`) - this installs the node dependencies, creates the S3 bucket (if it does not already exist), packages and uploads your serverless Express application assets to S3, uploads the API Swagger file to S3, and finally spins up a CloudFormation stack, which creates your API Gateway API and Lambda Function. +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, and wait several minutes for the status to change to `CREATE_COMPLETE`, 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-upload-update-function` (Windows users: `npm run win-package-upload-update-function`). This will compress `lambda.js`, `app.js`, `index.html`, and your `node_modules` directory into `lambda-function.zip`, upload that zip to S3, and update your Lambda function. + +To migrate an existing Node server: + +1. Copy the following files from the `example` directory: `api-gateway-event.json`, `cloudformation.json`, `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 `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 `package-function` script (`win-package-function` for Windows users) in `package.json` to include all files necessary to run your application. If everything you need is in a single child directory, this is as simple as changing `app.js` to `my-app-dir` (also remove `index.html` from that command). If you are using a build tool, you will instead want to add your build output directory to this command. +5. Run `npm run package-upload-update-function` (Windows users: `npm run win-package-upload-update-function`) to package (zip), upload (to S3), and update your Lambda function. + +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 upload-api-gateway-swagger && npm run update-stack`. If your API requires CORS, be sure to modify the two `options` methods defined in the Swagger file, otherwise you can safely remove them. Note: there is currently an issue with updating CloudFormation when it's not obvious that one of its resources has been modified; eg. the Swagger file is an external file hosted on S3. To work around this, simply update one of the resource's properties, such as the `Description` on the `ApiGatewayApi` resource. To modify your other AWS assets, make your changes to `cloudformation.json` and run `npm run update-stack`. Alternatively, you can manage these assets via the AWS console. + +### Getting the API Gateway event object +This package includes middleware to easily get the event object Lambda receives from API Gateway + +```js +const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware') +app.use(awsServerlessExpressMiddleware.eventContext()) +``` + +### Is AWS serverless right for my app? + +#### Pros + + - Pay for what you use + - No infrastructure to manage + - Auto-scaling with no configuration needed + - [Usage Plans](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html) + - [Caching](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html) + - [Authorization](http://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) + - [Staging](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-deploy-api.html) + - [SDK Generation](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html) + - [API Monitoring](http://docs.aws.amazon.com/apigateway/latest/developerguide/monitoring-cloudwatch.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 + - Multiple headers with same name not supported + - API Gateway has a timeout of 30 seconds, and Lambda has a maximum execution time of 5 minutes. diff --git a/aws-serverless-express/index.js b/aws-serverless-express/index.js new file mode 100644 index 0000000..8833042 --- /dev/null +++ b/aws-serverless-express/index.js @@ -0,0 +1,185 @@ +/* + * Copyright 2016-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +'use strict' +const http = require('http') + +function getPathWithQueryStringParams(event) { + const queryStringKeys = Object.keys(event.queryStringParameters || {}) + + if (queryStringKeys.length === 0) return event.path + + const queryStringParams = queryStringKeys.map(queryStringKey => `${queryStringKey}=${encodeURIComponent(event.queryStringParameters[queryStringKey])}`).join('&') + + return `${event.path}?${queryStringParams}` +} + +function mapApiGatewayEventToHttpRequest(event, context, socketPath) { + const headers = event.headers || {} // NOTE: Mutating event.headers; prefer deep clone of event.headers + const eventWithoutBody = Object.assign({}, event) + delete eventWithoutBody.body + + headers['x-apigateway-event'] = JSON.stringify(eventWithoutBody) + headers['x-apigateway-context'] = JSON.stringify(context) + + return { + method: event.httpMethod, + path: getPathWithQueryStringParams(event), + headers, + socketPath + // protocol: `${headers['X-Forwarded-Proto']}:`, + // host: headers.Host, + // hostname: headers.Host, // Alias for host + // port: headers['X-Forwarded-Port'] + } +} + +function forwardResponseToApiGateway(server, response, context) { + const gunzip = require('zlib').createGunzip() + let buf = [] + + let parsedResponse = null + + if (response.headers['content-encoding'] == "gzip") { + response.pipe(gunzip) + parsedResponse = gunzip + response.headers['content-encoding'] = undefined + response.headers['transfer-encoding'] = undefined + } else { + parsedResponse = response + } + + parsedResponse + .on('data', (chunk) => buf.push(chunk)) + .on('end', () => { + let body = Buffer.concat(buf) + const statusCode = response.statusCode + const headers = response.headers + + Object.keys(headers) + .forEach(h => { + if(Array.isArray(headers[h])) headers[h] = headers[h].join(',') + }) + + const contentType = headers['content-type'] + let isBase64Encoded + + if (server._binaryTypes.indexOf(contentType) !== -1) { + body = body.toString('base64') + isBase64Encoded = true + } else { + body = body.toString('utf8') + isBase64Encoded = false + } + + const successResponse = {statusCode, body, headers, isBase64Encoded} + console.log('Aqui: ', JSON.stringify(successResponse)) + context.succeed(successResponse) + }) +} + +function forwardConnectionErrorResponseToApiGateway(server, error, context) { + console.error(error) + const errorResponse = { + statusCode: 502, // "DNS resolution, TCP level errors, or actual HTTP parse errors" - https://nodejs.org/api/http.html#http_http_request_options_callback + body: '', + headers: {} + } + + context.succeed(errorResponse) +} + +function forwardLibraryErrorResponseToApiGateway(server, error, context) { + console.error(error) + const errorResponse = { + statusCode: 500, + body: '', + headers: {} + } + + context.succeed(errorResponse) +} + +function forwardRequestToNodeServer(server, event, context) { + const requestOptions = mapApiGatewayEventToHttpRequest(event, context, getSocketPath(server._socketPathSuffix)) + const req = http.request(requestOptions, (response) => forwardResponseToApiGateway(server, response, context)) + if (event.body) { + req.write(event.body) + } + req.on('error', (error) => forwardConnectionErrorResponseToApiGateway(server, error, context)) + .end() +} + +function startServer(server) { + return server.listen(getSocketPath(server._socketPathSuffix)) +} + +function getSocketPath(socketPathSuffix) { + return `/tmp/server${socketPathSuffix}.sock` +} + +exports.createServer = (requestListener, serverListenCallback, binaryTypes) => { + const server = http.createServer(requestListener) + + server._socketPathSuffix = 0 + server._binaryTypes = binaryTypes ? binaryTypes.slice() : [] + server.on('listening', () => { + server._isListening = true + + if (serverListenCallback) serverListenCallback() + }) + server.on('close', () => { + server._isListening = false + }) + .on('error', (err) => { + if (err.code === 'EADDRINUSE') { + console.warn(`EADDRINUSE ${getSocketPath(server._socketPathSuffix)} incrementing socketPathSuffix.`) + ++server._socketPathSuffix + server.close(() => startServer(server)) + } + }) + + return server +} + +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) { + console.log('There was an error:' + error) + forwardLibraryErrorResponseToApiGateway(server, error, context) + } + }) + } + } catch (error) { + forwardLibraryErrorResponseToApiGateway(server, error, context) + } +} + +if (process.env.NODE_ENV === 'test') { + exports.getPathWithQueryStringParams = getPathWithQueryStringParams + exports.mapApiGatewayEventToHttpRequest = mapApiGatewayEventToHttpRequest + exports.forwardResponseToApiGateway = forwardResponseToApiGateway + exports.forwardConnectionErrorResponseToApiGateway = forwardConnectionErrorResponseToApiGateway + exports.forwardLibraryErrorResponseToApiGateway = forwardLibraryErrorResponseToApiGateway + exports.forwardRequestToNodeServer = forwardRequestToNodeServer + exports.startServer = startServer + exports.getSocketPath = getSocketPath +} diff --git a/aws-serverless-express/middleware.js b/aws-serverless-express/middleware.js new file mode 100644 index 0000000..dc5bd28 --- /dev/null +++ b/aws-serverless-express/middleware.js @@ -0,0 +1,23 @@ +module.exports.eventContext = options => (req, res, next) => { + options = options || {} // defaults: {reqPropKey: 'apiGateway', deleteHeaders: true} + const reqPropKey = options.reqPropKey || 'apiGateway' + const deleteHeaders = options.deleteHeaders === undefined ? true : options.deleteHeaders + + if (!req.headers['x-apigateway-event'] || !req.headers['x-apigateway-context']) { + console.error('Missing x-apigateway-event or x-apigateway-context header(s)') + next() + return + } + + req[reqPropKey] = { + event: JSON.parse(req.headers['x-apigateway-event']), + context: JSON.parse(req.headers['x-apigateway-context']) + } + + if (deleteHeaders) { + delete req.headers['x-apigateway-event'] + delete req.headers['x-apigateway-context'] + } + + next() +} diff --git a/aws-serverless-express/package.json b/aws-serverless-express/package.json new file mode 100644 index 0000000..b7d3555 --- /dev/null +++ b/aws-serverless-express/package.json @@ -0,0 +1,62 @@ +{ + "name": "aws-serverless-express", + "version": "1.3.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.", + "keywords": [ + "aws", + "serverless", + "api", + "gateway", + "lambda", + "express" + ], + "homepage": "https://github.com/awslabs/aws-serverless-express", + "bugs": { + "url": "https://github.com/awslabs/aws-serverless-express/issues" + }, + "license": "Apache-2.0", + "files": [ + "index.js", + "middleware.js" + ], + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/awslabs/aws-serverless-express.git" + }, + "engines": { + "node": ">=4" + }, + "devDependencies": { + "jest": "^16.0.2" + }, + "scripts": { + "test": "jest" + }, + "gitHead": "c1bb8d2bf17f2c9902e99d210d030a00ad285b23", + "_id": "aws-serverless-express@1.3.0", + "_shasum": "b7b52a30a5bccc7c77c8d24f2ccdbf948a138c6d", + "_from": "aws-serverless-express@>=1.2.0 <2.0.0", + "_npmVersion": "3.6.0", + "_nodeVersion": "5.6.0", + "_npmUser": { + "name": "brettstack", + "email": "brett.j.andrews@gmail.com" + }, + "dist": { + "shasum": "b7b52a30a5bccc7c77c8d24f2ccdbf948a138c6d", + "tarball": "https://registry.npmjs.org/aws-serverless-express/-/aws-serverless-express-1.3.0.tgz" + }, + "maintainers": [ + { + "name": "brettstack", + "email": "brett.j.andrews@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/aws-serverless-express-1.3.0.tgz_1485280882922_0.7727212074678391" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/aws-serverless-express/-/aws-serverless-express-1.3.0.tgz" +} diff --git a/claudia.json b/claudia.json index 18c5d09..2ba81a7 100644 --- a/claudia.json +++ b/claudia.json @@ -1,10 +1,10 @@ { "lambda": { - "role": "estudos-estrategicos-executor", - "name": "estudos-estrategicos", + "role": "SAPO-executor", + "name": "SAPO", "region": "us-east-1" }, "api": { - "id": "8zs8jls20g" + "id": "2d3n35t39a" } } \ No newline at end of file diff --git a/lambda.js b/lambda.js index 5b1e8b4..3249583 100644 --- a/lambda.js +++ b/lambda.js @@ -1,5 +1,5 @@ 'use strict' -const awsServerlessExpress = require('aws-serverless-express') +const awsServerlessExpress = require('./aws-serverless-express/index.js') const app = require('./server') const server = awsServerlessExpress.createServer(app) -exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context) +exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context) \ No newline at end of file diff --git a/package.json b/package.json index 50b1b98..4d5b479 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "author": "Luciano P. Franca", "license": "MIT", "dependencies": { - "aws-serverless-express": "^1.2.0", + "aws-serverless-express": "^1.3.0", "better-require": "0.0.3", "bluebird": "^3.4.6", "body-parser": "~1.0.1", diff --git a/test.js b/test.js new file mode 100644 index 0000000..e69de29