├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── package-lock.json ├── package.json ├── src ├── index.js └── logger.js └── test └── index.spec.js /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | .nyc_output 4 | coverage 5 | node_modules 6 | .history/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log / Release Notes 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | 8 | ## [2.12.0] - 2021-08-07 9 | ### Added 10 | - `routes` to `unknown` as 5th parameter 11 | - `statusCode: 405` to `defaultUnknownRoute` when other methods for the same path exist 12 | 13 | ## [2.11.0] - 2021-06-06 14 | ### Added 15 | - `error.name` pass-through to `formatError` 16 | 17 | ## [2.10.0] - 2020-04-27 18 | ### Added 19 | - `patch` route/verb support 20 | 21 | ## [2.9.1] - 2019-09-04 22 | ### Fixed 23 | - Compound value `content-type` header not identifying correctly 24 | 25 | ## [2.9.0] - 2019-08-16 26 | ### Added 27 | - `normalizeHeaders` options to lower-case all header names 28 | 29 | ## [2.8.0] - 2019-07-02 30 | ### Added 31 | - `beforeRoute` middleware 32 | 33 | ## [2.7.0] - 2019-06-19 34 | ### Added 35 | - `assumeJson` option 36 | 37 | ## [2.6.0] - 2019-06-19 38 | ### Added 39 | - export `getTraceId` 40 | 41 | ## [2.5.1] - 2019-05-20 42 | ### Fixed 43 | - Syntax error 44 | 45 | ## [2.5.0] - 2019-05-20 46 | ### Added 47 | - Body parsing support for `application/x-www-form-urlencoded` 48 | - `event.rawBody` as original, unparsed body when `event.body` is parsed 49 | ### Fixed 50 | - Check `Content-Type` for `application/json` before parsing as JSON 51 | 52 | ## [2.4.1] - 2019-05-01 53 | ### Fixed 54 | - Documentation errors 55 | 56 | ## [2.4.0] - 2018-12-01 57 | ### Fixed 58 | - Documentation errors 59 | 60 | ## [2.3.0] - 2018-10-8 61 | ### Added 62 | - Initial OSS release 63 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | There are a few guidelines that we need contributors to follow so that we are able to process requests as efficiently as possible. If you have any questions or concerns please feel free to contact us at [opensource@nike.com](mailto:opensource@nike.com). 4 | 5 | ## Getting Started 6 | 7 | * Review our [Code of Conduct](https://github.com/Nike-Inc/nike-inc.github.io/blob/master/CONDUCT.md) 8 | * Submit the [Individual Contributor License Agreement](https://www.clahub.com/agreements/Nike-Inc/fastbreak) 9 | * Make sure you have a [GitHub account](https://github.com/signup/free) 10 | * Submit a ticket for your issue, assuming one does not already exist. 11 | * Clearly describe the issue including steps to reproduce when it is a bug. 12 | * Make sure you fill in the earliest version that you know has the issue. 13 | * Fork the repository on GitHub 14 | 15 | ## Making Changes 16 | 17 | * Create a topic branch off of `master` before you start your work. 18 | * Please avoid working directly on the `master` branch. 19 | * Make commits of logical units. 20 | * You may be asked to squash unnecessary commits down to logical units. 21 | * Check for unnecessary whitespace with `git diff --check` before committing. 22 | * Write meaningful, descriptive commit messages. 23 | * Please follow existing code conventions when working on a file. 24 | 25 | ## Submitting Changes 26 | 27 | * Push your changes to a topic branch in your fork of the repository. 28 | * Submit a pull request to the repository in the Nike-Inc organization. 29 | * After feedback has been given we expect responses within two weeks. After two weeks we may close the pull request if it isn't showing any activity. 30 | * Bug fixes or features that lack appropriate tests may not be considered for merge. 31 | * Changes that lower test coverage may not be considered for merge. 32 | 33 | # Additional Resources 34 | 35 | * [General GitHub documentation](https://help.github.com/) 36 | * [GitHub pull request documentation](https://help.github.com/send-pull-requests/) 37 | * [Nike's Code of Conduct](https://github.com/Nike-Inc/nike-inc.github.io/blob/master/CONDUCT.md) 38 | * [Nike's Individual Contributor License Agreement](https://www.clahub.com/agreements/Nike-Inc/fastbreak) 39 | * [Nike OSS](https://nike-inc.github.io/) 40 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Nike, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lambda Router 2 | 3 | A small and simple router to simplify managing routers in a NodeJS Lambda function. 4 | 5 | **NOTE**: Prior to v2 (there was no v1) this package was owned by another maintainer ([yu0819ki](https://github.com/yu0819ki)). You can find the [old lamdba-router package here](https://github.com/yu0819ki/lambda-router). This is effectively an entirely different package. 6 | 7 | # Installation 8 | 9 | ``` 10 | npm install lambda-router 11 | ``` 12 | 13 | # Quick Start 14 | ```javascript 15 | const { Router } = require('lambda-router') 16 | const router = Router({ 17 | logger: console // uses logger-wrapper. 18 | includeErrorStack: process.env.stage !== 'prod' 19 | }) 20 | 21 | router.post('/v1/endpoint', service.create) 22 | router.get('/v1/endpoint/{id}', service.get) 23 | router.put('/v1/endpoint/{id}', service.put) 24 | router.delete('/v1/endpoint/{id}', service.delete) 25 | router.unknown((event, { response }, path, method, routes) => { 26 | return response(404, { 27 | message: `You dun screwed up, now. ${path} doesn't exist!` 28 | }) 29 | }) 30 | 31 | async function handler (lambdaEvent, context) { 32 | context.callbackWaitsForEmptyEventLoop = false 33 | router.formatError((statusCode, error) => { 34 | error.errorType = getErrorType(statusCode) // custom method 35 | return error 36 | }) 37 | let result = await router.route(lambdaEvent, context) 38 | 39 | return result.response 40 | } 41 | ``` 42 | 43 | # API 44 | 45 | ```javascript 46 | function Router ({ 47 | logger, // logger-wrapper 48 | extractPathParameters = true, // merge proxy path parameters into event.pathParameters 49 | includeTraceId = true, // include TraceId header 50 | inluceErrorStack = false, // include stack traces with error responses 51 | cors = true, // include CORS header, can be a string to set header value or true for '*' 52 | parseBody = true, // parse JSON or URL encoded body into event 53 | decodeEvent = true, // merge URI decoded parameters for path and querystring 54 | normalizeHeaders = false // If true all headers will be lowercased, and the original headers will be placed on event.rawHeaders 55 | } = {}) { 56 | route: async (event, context) => Promise<{ 57 | isOk, 58 | endpoint, 59 | uri, 60 | response 61 | } 62 | get|post|put|delete: async (pattern, handler) => {} 63 | unknown: (event, context, path, method, routes) => {} 64 | beforeRoute: async (event, context, path, method) 65 | } 66 | ``` 67 | 68 | ## Body Parsing 69 | 70 | If `parseBody` is true and the request `Content-Type` is `application/json` or `application/x-www-form-urlencoded` the `event.body` will be replaced with a parsed object, and `event.rawBody` will contain the original, unparsed body string. 71 | 72 | # Routes 73 | 74 | Routes can be registered with any of the http verb methods. 75 | 76 | `router.[get|post|put|delete](routePattern: string, handler: (event, context) => Object|Promise)` 77 | 78 | Route matching is done either literally or by path token. When a route is matched it's handler function is invoked, and the result is used as the response body. If a route pattern matches the path exactly it will be selected. If not, the route will try to match by token, replacing anything in curly braces with values from the path. 79 | 80 | For example, the path `/v1/endpoint/1234` will match the route pattern `'/v1/endpoint/{id}'`, because the `{id}` section will be treated as a path token and match the value `1234`. 81 | 82 | If the router option `extractPathParameters` is set, the `event.pathParameters` will receive the `id` value as `event.pathParameters.id: 1234`. Similarly, querystring parameters will be merged into `event.queryStringParameters`. 83 | 84 | Route handlers that return an object will get a default status code of 200, and the object will be passed to `JSON.stringify` before being returned. Handlers that throw an error will get a default status code of 500. If you throw an error object with a `statusCode` property it's value will replace the default 500 status code. To customize status code for successful responses see the **Custom Response** section below. 85 | 86 | 87 | ## The Unknown Handler 88 | 89 | When no route is matched the unknown handler is invoked. The default unknown handler will return a canned response containing the unmatched path, with a 404. You can replace the unknown handler by provider your own to `router.unknown`. This handler will function as a normal handler, returning a 200 unless it throws an error. Since errors default to status code 500, you should probably manually set the status code to 404. 90 | 91 | There is a special case on the default unknown handler when the request has a match on the path but not on the method. In this case a 405 with a correct `Allow` header will be returned. 92 | 93 | ## Middleware 94 | 95 | You can use the `beforeRoute` method to define middleware that will run before attempting to match a registered route. This is useful for mutating the incoming event or context, or for running validations at the global level: 96 | 97 | ```js 98 | function redactAuthToken (event, context, path, method) { 99 | event.headers['Authorization'] = '--redacted' 100 | } 101 | 102 | function validateContentType (event, context, path, method) { 103 | if (!event.headers['Content-Type'].includes('application/json')) { 104 | const error = new Error('Content-Type must be JSON') 105 | error.statusCode = 400 106 | throw error 107 | } 108 | } 109 | 110 | // these will both run before any route matching occurs 111 | router.beforeRoute(redactAuthToken) 112 | router.beforeRoute(validateContentType) 113 | 114 | router.post('/v1/endpoint', service.create) 115 | router.get('/v1/endpoint/{id}', service.get) 116 | ``` 117 | 118 | # Custom Response 119 | 120 | The `context` object, the second parameter to route handlers, has a `response` property function. It can be used to provide custom status codes, custom headers, and control body serialization. 121 | 122 | ```javascript 123 | 124 | router.post('/v1/endpoint', handleDelete) 125 | 126 | async function handleCreate({ headers }, { path, response }) 127 | let dbItem = await createNewItem() 128 | return response(201, result, { Location: 'https://' + headers.Host + path + '/' + dbItem.id }) 129 | 130 | async function download({ headers }, { path, response }) 131 | let file = getFileBuffer() 132 | return response(201, file, { 'Content-Type': 'application/octet-stream' }) 133 | ``` 134 | 135 | # Custom Headers 136 | 137 | Fully-custom responses are sometimes undesirable, as they avoid some of the automatic behavior of normal respones (such as error formatting). If your only goal is to set a custom response header you can use `response.setHeader` 138 | 139 | ```javascript 140 | router.post('/route', (_, { response }) => { 141 | response.setHeader('Location', 'something') 142 | return { message: 'success' } 143 | }) 144 | ``` 145 | 146 | 147 | # Error Formatting 148 | 149 | By default error's are serialized as responses, and either use the `error.statusCode` or a default 500 status code. If you want to control the error object, or perform custom instrumentation for errors, you can provide your own error formatter. The error formatter will be called with the status code and the error and must return the error that will be serialized for the response. 150 | 151 | ```javascript 152 | router.formatError((statusCode, error) => { 153 | error.errorType = getErrorType(statusCode) // custom method 154 | return error 155 | }) 156 | ``` 157 | 158 | # Router response 159 | 160 | When you call `router.route` you must provide the lambda event and context. 161 | 162 | ```javascript 163 | let result = await router.route(event, context) 164 | ``` 165 | 166 | Optionally you can provide the the path and/or method to route on, in case the default selection method does not match your needs 167 | 168 | ```javascript 169 | let result = await router.route(event, context, customPath, customMethod) 170 | ``` 171 | 172 | The router will match the route and return a promise that will wait on the matched route handler. The result looks like this 173 | 174 | ```javascript 175 | { 176 | isOk: boolean // is the status code a 2xx 177 | endpoint: string // the route pattern that matched 178 | uri: string // the real path from the event 179 | response: { 180 | statusCode: number, 181 | body: string // stringified route handler response, or custom response 182 | headers: {} // default headers or custom response headers 183 | } 184 | } 185 | 186 | ``` 187 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lambda-router", 3 | "version": "2.12.0", 4 | "description": "A router to simplify AWS Lambda Functions.", 5 | "main": "src/index.js", 6 | "files": [ 7 | "src" 8 | ], 9 | "engines": { 10 | "node": ">=8.10" 11 | }, 12 | "scripts": { 13 | "lint": "eslint -c package.json \"{src,test}/**/*.js\"", 14 | "check": "npm run style && npm run lint", 15 | "test": "npm run check && npm run test:unit", 16 | "test:unit": "ava", 17 | "test:watch": "ava --watch", 18 | "test:coverage": "nyc --check-coverage --lines 80 ava", 19 | "test:coverage:open": "npm run test:coverage; npm run report:open", 20 | "report": "nyc report --reporter=html", 21 | "report:open": "npm run report && open coverage/index.html", 22 | "test:ci": "npm run check && ava --tap | tap-xunit > ~/reports/ava.xml && npm run test:coverage && npm run report:ci", 23 | "style": "prettier --config package.json --write \"{src,test}/**/*.js\"", 24 | "jsdoc:generate": "jsdoc ./src/index.js -d ./docs/", 25 | "release": "np" 26 | }, 27 | "repository": { 28 | "type": "git", 29 | "url": "git@github.com:Nike-Inc/lambda-router.git" 30 | }, 31 | "keywords": [ 32 | "aws", 33 | "lambda", 34 | "router" 35 | ], 36 | "author": "Tim Kye", 37 | "license": "Apache-2", 38 | "dependencies": { 39 | "uuid": "^3.3.2" 40 | }, 41 | "devDependencies": { 42 | "@kyeotic/eslint-config": "^0.9.0", 43 | "ava": "^3.15.0", 44 | "aws-sdk": "^2.4.8", 45 | "chokidar-cli": "^2.1.0", 46 | "eslint": "^5.16.0", 47 | "expect": "1.20.2", 48 | "jsdoc": "^3.4.3", 49 | "np": "^7.5.0", 50 | "nyc": "latest", 51 | "prettier": "^1.18.2", 52 | "sinon": "^7.3.2" 53 | }, 54 | "prettier": { 55 | "tabWidth": 2, 56 | "semi": false, 57 | "singleQuote": true, 58 | "printWidth": 100 59 | }, 60 | "np": { 61 | "yarn": false 62 | }, 63 | "eslintConfig": { 64 | "extends": [ 65 | "@kyeotic/eslint-config/node" 66 | ] 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const qs = require('querystring') 4 | const uuid = require('uuid/v4') 5 | const { loggerWrapper } = require('./logger') 6 | 7 | const CUSTOM_RESPONSE = Symbol('lambda-router:custom-response') 8 | const TRACE_ID = Symbol('trace-id') 9 | 10 | module.exports = { 11 | Router, 12 | getTraceId, 13 | createProxyResponse 14 | } 15 | 16 | function Router({ 17 | logger, 18 | extractPathParameters = true, 19 | // default to false, otherwise adding this would be a breaking change 20 | // TODO: v3, default true 21 | trimTrailingSlash = false, 22 | includeTraceId = true, 23 | includeErrorStack = false, 24 | cors = true, 25 | parseBody = true, 26 | assumeJson = false, 27 | decodeEvent = true, 28 | // default to false, otherwise adding this would be a breaking change 29 | // TODO: v3, default true 30 | normalizeHeaders = false 31 | } = {}) { 32 | const originalLogger = logger 33 | 34 | if (originalLogger && originalLogger.events && originalLogger.setKey) { 35 | originalLogger.events.on('beforeHandler', (event, context) => { 36 | originalLogger.setKey('traceId', getTraceId(event, context)) 37 | }) 38 | } 39 | 40 | logger = loggerWrapper(logger) 41 | const routes = [] 42 | const addRoute = (method, path, handler) => { 43 | routes.push({ method, path, handler }) 44 | } 45 | 46 | const middleware = [] 47 | const addMiddleware = handler => { 48 | if (typeof handler === 'function') middleware.push(handler) 49 | } 50 | 51 | let unknownRouteHandler = defaultUnknownRoute 52 | let defaultHeaders = { 53 | 'Content-Type': 'application/json' 54 | } 55 | if (cors) { 56 | defaultHeaders['Access-Control-Allow-Origin'] = typeof cors === 'boolean' ? '*' : cors 57 | } 58 | 59 | // External hooks 60 | let onErrorFormat 61 | 62 | const route = async (event, context, requestPath, httpMethod) => { 63 | let statusCode, body 64 | let requestHeaders = normalizeRequestHeaders(event.headers) 65 | let headers = { ...defaultHeaders } 66 | // Safety Checks 67 | if (context.response) { 68 | let message = 69 | 'context.response has already been assigned. Lambda-router reserves this property for custom responses.' 70 | logger.error(message) 71 | return Promise.reject(new Error(message)) 72 | } 73 | // Custom Response 74 | context.response = customResponse.bind(null, context) 75 | // Allow setting custom header without full-custom response 76 | context.response.setHeader = (header, value) => { 77 | headers[header] = value 78 | } 79 | 80 | // Allow method and path overrides 81 | httpMethod = httpMethod || event.method || event.httpMethod 82 | requestPath = requestPath || event.path || event.resourcePath || event.resource 83 | 84 | if (trimTrailingSlash) { 85 | requestPath = requestPath.replace(/\/$/, '') 86 | } 87 | 88 | // HTTP/2 says headers all always lowercase 89 | if (normalizeHeaders) { 90 | event.rawHeaders = event.headers 91 | event.headers = requestHeaders 92 | } 93 | 94 | let route = getRoute(routes, event, requestPath, httpMethod, extractPathParameters) 95 | let hasBody = event.body && typeof event.body === 'string' 96 | let contentType = requestHeaders && requestHeaders['content-type'] 97 | let jsonBody = 98 | hasBody && (hasHeaderValue(contentType, 'application/json') || (!contentType && assumeJson)) 99 | let urlEncodedBody = hasBody && hasHeaderValue(contentType, 'application/x-www-form-urlencoded') 100 | 101 | // Parse and decode 102 | try { 103 | if (parseBody) { 104 | event.rawBody = event.body 105 | if (jsonBody) event.body = JSON.parse(event.body) 106 | else if (urlEncodedBody) event.body = qs.parse(event.body) 107 | } 108 | if (decodeEvent) { 109 | logger.debug('decoding parameters') 110 | event.pathParameters = decodeProperties(event.pathParameters || {}) 111 | event.queryStringParameters = decodeProperties(event.queryStringParameters || {}) 112 | } 113 | } catch (error) { 114 | logger.error('route error', error.toString(), error.stack) 115 | return createResponse( 116 | 400, 117 | { message: 'Malformed request' }, 118 | defaultHeaders, 119 | route.path, 120 | requestPath 121 | ) 122 | } 123 | 124 | // Route 125 | if (includeTraceId) context.traceId = headers['X-Correlation-Id'] = getTraceId(event, context) 126 | try { 127 | for (let fn of middleware) { 128 | await fn(event, context, requestPath, httpMethod) 129 | } 130 | 131 | let result = await (route 132 | ? route.handler(event, context) 133 | : unknownRouteHandler(event, context, requestPath, httpMethod, routes)) 134 | if (result && result._isCustomResponse === CUSTOM_RESPONSE) { 135 | statusCode = result.statusCode 136 | body = result.body 137 | headers = { ...defaultHeaders, ...result.headers } 138 | } else { 139 | statusCode = 200 140 | body = result 141 | } 142 | } catch (error) { 143 | statusCode = error.statusCode || 500 144 | body = { 145 | ...error, 146 | // The spread doesn't get the non-enumerable message 147 | message: error.message, 148 | name: error.name, 149 | stack: includeErrorStack && error.stack 150 | } 151 | if (error.headers) { 152 | headers = { ...headers, ...error.headers } 153 | } 154 | if (onErrorFormat && typeof onErrorFormat === 'function') { 155 | body = onErrorFormat(statusCode, body) 156 | } 157 | } 158 | 159 | return createResponse(statusCode, body, headers, route && route.path, requestPath) 160 | } 161 | 162 | // Bound router functions 163 | return { 164 | beforeRoute: addMiddleware, 165 | get: addRoute.bind(null, 'GET'), 166 | post: addRoute.bind(null, 'POST'), 167 | put: addRoute.bind(null, 'PUT'), 168 | delete: addRoute.bind(null, 'DELETE'), 169 | patch: addRoute.bind(null, 'PATCH'), 170 | unknown: handler => { 171 | unknownRouteHandler = handler 172 | }, 173 | formatError: handler => { 174 | onErrorFormat = handler 175 | }, 176 | route 177 | } 178 | } 179 | 180 | function customResponse(context, statusCode, body, headers) { 181 | let response = { 182 | statusCode, 183 | body, 184 | headers 185 | } 186 | if (context.includeTraceId && context.traceId) { 187 | headers['X-Correlation-Id'] = context.traceId 188 | } 189 | Object.defineProperty(response, '_isCustomResponse', { 190 | enumerable: false, 191 | configurable: false, 192 | value: CUSTOM_RESPONSE 193 | }) 194 | return response 195 | } 196 | 197 | function getRoute(routes, event, eventPath, method, tokenizePathParts) { 198 | let route = routes.find(r => { 199 | return eventPath === r.path && method === r.method 200 | }) 201 | 202 | if (!route) { 203 | let tokens 204 | route = routes.find(r => { 205 | if (method !== r.method) return false 206 | tokens = doPathPartsMatch(eventPath, r) 207 | return !!tokens 208 | }) 209 | if (tokenizePathParts && tokens) { 210 | if (!event.pathParameters) event.pathParameters = {} 211 | Object.assign(event.pathParameters, tokens) 212 | } 213 | } 214 | 215 | return route 216 | } 217 | 218 | function doPathPartsMatch(eventPath, route) { 219 | const eventPathParts = eventPath.split('/') 220 | const routePathParts = route.path.split('/') 221 | 222 | // Fail fast if they're not the same length 223 | if (eventPathParts.length !== routePathParts.length) return false 224 | let tokens = {} 225 | 226 | // Start with 1 because the url should always start with the first back slash 227 | for (let i = 1; i < eventPathParts.length; ++i) { 228 | const pathPart = eventPathParts[i] 229 | const routePart = routePathParts[i] 230 | 231 | // If the part is a curly braces value 232 | let pathPartMatch = /\{(\w+)}/g.exec(routePart) 233 | if (pathPartMatch) { 234 | tokens[pathPartMatch[1]] = pathPart 235 | continue 236 | } 237 | 238 | // Fail fast if a part doesn't match 239 | if (routePart !== pathPart) { 240 | return false 241 | } 242 | } 243 | 244 | return tokens 245 | } 246 | 247 | function defaultUnknownRoute(event, context, path, httpMethod, routes) { 248 | const methodMatches = routes 249 | .filter(r => { 250 | return path === r.path 251 | }) 252 | .map(r => r.method) 253 | 254 | const error = new Error(`Endpoint not supported: ${httpMethod}${path}`) 255 | error.statusCode = 404 256 | 257 | if (methodMatches.length) { 258 | error.statusCode = 405 259 | error.headers = { 260 | Allow: methodMatches.join(',') 261 | } 262 | } 263 | 264 | throw error 265 | } 266 | 267 | function createResponse(statusCode, body, headers, endpoint, uri) { 268 | return { 269 | endpoint, 270 | uri, 271 | isOk: statusCode.toString()[0] === '2', 272 | response: createProxyResponse(statusCode, body, headers) 273 | } 274 | } 275 | 276 | function createProxyResponse(statusCode, body, headers = {}) { 277 | if (headers['Content-Type'] === undefined) headers['Content-Type'] = 'application/json' 278 | // output follows the format described here 279 | // http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html?shortFooter=true#api-gateway-simple-proxy-for-lambda-output-format 280 | return { 281 | statusCode, 282 | body: typeof body === 'object' ? JSON.stringify(body) : body, 283 | headers: { ...headers } 284 | } 285 | } 286 | 287 | function getTraceId(event, context) { 288 | const traceId = 289 | (event.headers && 290 | (event.headers['X-Trace-Id'] || 291 | event.headers['X-TRACE-ID'] || 292 | event.headers['x-trace-id'] || 293 | event.headers['X-Correlation-Id'] || 294 | event.headers['X-CORRELATION-ID'] || 295 | event.headers['x-correlation-id'])) || 296 | context.awsRequestId || 297 | uuid() 298 | context[TRACE_ID] = traceId 299 | return traceId 300 | } 301 | 302 | function decodeProperties(obj) { 303 | return ( 304 | obj && 305 | Object.keys(obj).reduce((r, key) => { 306 | r[key] = decodeURIComponent(obj[key]) 307 | return r 308 | }, {}) 309 | ) 310 | } 311 | 312 | function hasHeaderValue(header, value) { 313 | if (!header || !value) return false 314 | header = header.toLowerCase() 315 | value = value.toLowerCase() 316 | if (header === value) return true 317 | let headerParts = header.split(';') 318 | return headerParts.includes(value) 319 | } 320 | 321 | function normalizeRequestHeaders(reqHeaders = {}) { 322 | return Object.keys(reqHeaders).reduce((headers, name) => { 323 | headers[name.toLowerCase()] = reqHeaders[name] 324 | return headers 325 | }, {}) 326 | } 327 | -------------------------------------------------------------------------------- /src/logger.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const assert = require('assert') 3 | 4 | const logLevels = ['DEBUG', 'INFO', 'WARN', 'ERROR'] 5 | // eslint-disable-next-line no-empty-function 6 | const noop = () => {} 7 | 8 | const makeLogWrapper = (logger, prop) => { 9 | let func 10 | if (logger[prop] && typeof logger[prop] === 'function') { 11 | func = logger[prop] 12 | } else { 13 | func = 14 | logger.minimumLogLevel !== undefined 15 | ? // eslint-disable-next-line no-console 16 | (console[prop] || console.log).bind(console) 17 | : noop 18 | } 19 | return (...args) => { 20 | if ( 21 | logger.minimumLogLevel !== undefined && 22 | logLevels.indexOf(logger.minimumLogLevel) > logLevels.indexOf(prop.toUpperCase()) 23 | ) 24 | return 25 | return func(...args) 26 | } 27 | } 28 | 29 | function loggerWrapper(loggerArg) { 30 | const logger = loggerArg || {} 31 | if (logger.minimumLogLevel !== undefined) { 32 | assert( 33 | logLevels.indexOf(logger.minimumLogLevel) !== -1, 34 | `"minimumLogLevel" must be one of: ${logLevels.join(', ')} or "undefined"` 35 | ) 36 | } 37 | 38 | return { 39 | error: makeLogWrapper(logger, 'error'), 40 | warn: makeLogWrapper(logger, 'warn'), 41 | info: makeLogWrapper(logger, 'info'), 42 | debug: makeLogWrapper(logger, 'debug') 43 | } 44 | } 45 | 46 | module.exports = { 47 | loggerWrapper 48 | } 49 | -------------------------------------------------------------------------------- /test/index.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint no-unused-vars:0 no-empty-function:0 */ 2 | 'use strict' 3 | 4 | const test = require('ava') 5 | const qs = require('querystring') 6 | const sinon = require('sinon') 7 | const { Router } = require('../src/index') 8 | 9 | test('GET adds a route to the routes list.', async t => { 10 | t.plan(1) 11 | let router = Router() 12 | router.get('/route', () => { 13 | t.pass('called get') 14 | }) 15 | await router.route({}, {}, '/route', 'GET') 16 | }) 17 | 18 | test('GET matches with querystring.', async t => { 19 | t.plan(1) 20 | let router = Router() 21 | router.get('/route', ({ queryStringParameters: { name } }) => { 22 | t.is(name, 'tim', 'got qeury') 23 | }) 24 | await router.route( 25 | { 26 | path: '/route', 27 | httpMethod: 'GET', 28 | queryStringParameters: { name: 'tim' } 29 | }, 30 | {} 31 | ) 32 | }) 33 | 34 | test('POST adds a route to the routes list.', async t => { 35 | t.plan(1) 36 | let router = Router() 37 | router.post('/route', () => { 38 | t.pass('called post') 39 | }) 40 | await router.route({}, {}, '/route', 'POST') 41 | }) 42 | 43 | test('PUT adds a route to the routes list.', async t => { 44 | t.plan(1) 45 | let router = Router() 46 | router.put('/route', () => { 47 | t.pass('called put') 48 | }) 49 | await router.route({}, {}, '/route', 'PUT') 50 | }) 51 | 52 | test('DELETE adds a route to the routes list.', async t => { 53 | t.plan(1) 54 | let router = Router() 55 | router.delete('/route', () => { 56 | t.pass('called delete') 57 | }) 58 | await router.route({}, {}, '/route', 'DELETE') 59 | }) 60 | 61 | test('PATCH adds a route to the routes list.', async t => { 62 | t.plan(1) 63 | let router = Router() 64 | router.patch('/route', () => { 65 | t.pass('called patch') 66 | }) 67 | await router.route({}, {}, '/route', 'PATCH') 68 | }) 69 | 70 | test('Unknown route returns error.', async t => { 71 | t.plan(4) 72 | let router = Router() 73 | let result = await router.route({ method: 'DELETE', path: '/route' }, {}) 74 | t.is(result.endpoint, undefined, 'no endpoint') 75 | t.is(result.uri, '/route', 'has uri') 76 | t.is(result.response.statusCode, 404, 'has uri') 77 | t.truthy(result.response.body.includes('Endpoint not supported: DELETE/route'), 'has error') 78 | }) 79 | 80 | test('Unknown route returns error 405 when methods are available', async t => { 81 | t.plan(5) 82 | let router = Router() 83 | router.put('/route', () => { 84 | t.fail('called put') 85 | }) 86 | router.post('/route', () => { 87 | t.fail('called post') 88 | }) 89 | let result = await router.route({ method: 'DELETE', path: '/route' }, {}) 90 | t.is(result.endpoint, undefined, 'no endpoint') 91 | t.is(result.uri, '/route', 'has uri') 92 | t.is(result.response.statusCode, 405, 'has status') 93 | t.is(result.response.headers.Allow, 'PUT,POST') 94 | t.truthy(result.response.body.includes('Endpoint not supported: DELETE/route'), 'has error') 95 | }) 96 | 97 | test('unknown set the unknown route.', async t => { 98 | t.plan(1) 99 | let router = Router() 100 | router.unknown(() => { 101 | t.pass('called unknown') 102 | }) 103 | await router.route({}, {}, '/route', 'POST') 104 | }) 105 | 106 | test('unknown handler can use custom responses.', async t => { 107 | t.plan(2) 108 | let router = Router() 109 | router.unknown((event, { response }, path, method) => { 110 | return response(404, { 111 | message: `You dun screwed up, now. ${path} doesn't exist!` 112 | }) 113 | }) 114 | let result = await router.route({}, {}, '/route', 'POST') 115 | t.is(result.response.statusCode, 404, 'status code') 116 | t.is( 117 | JSON.parse(result.response.body).message, 118 | `You dun screwed up, now. ${'/route'} doesn't exist!`, 119 | 'got message' 120 | ) 121 | }) 122 | 123 | test('GET routes with trialing slash', async t => { 124 | t.plan(1) 125 | let router = Router({ trimTrailingSlash: true }) 126 | router.get('/route', () => { 127 | t.pass('called get') 128 | }) 129 | await router.route({}, {}, '/route/', 'GET') 130 | }) 131 | 132 | test('trialing slash causes unknown route', async t => { 133 | t.plan(1) 134 | let router = Router({ trimTrailingSlash: false }) 135 | router.get('/route', () => { 136 | t.fail('called get') 137 | }) 138 | router.unknown(() => { 139 | t.pass('called unknown') 140 | }) 141 | await router.route({}, {}, '/route/', 'GET') 142 | }) 143 | 144 | test('GET result has uri and endpoint.', async t => { 145 | t.plan(2) 146 | let router = Router() 147 | router.get('/route/{id}', () => {}) 148 | let result = await router.route({}, {}, '/route/1234', 'GET') 149 | t.is(result.endpoint, '/route/{id}', 'has endpoint') 150 | t.is(result.uri, '/route/1234', 'has uri') 151 | }) 152 | 153 | test('route matches on the GET handler', t => { 154 | let router = Router() 155 | const getHandler = () => t.pass('Handler called') 156 | const postHandler = () => t.fail('Wrong handler called') 157 | 158 | router.post('/post', postHandler) 159 | router.get('/get', getHandler) 160 | 161 | return router.route({ resourcePath: '/get', method: 'GET' }, {}) 162 | }) 163 | 164 | test('route matches on the method if the path are the same', t => { 165 | let router = Router() 166 | const getHandler = () => t.pass('Handler called') 167 | const postHandler = () => t.fail('Wrong handler called') 168 | 169 | router.get('/get', getHandler) 170 | router.post('/get', postHandler) 171 | 172 | return router.route({ resourcePath: '/get', method: 'GET' }, {}) 173 | }) 174 | 175 | test('route matches on the proper url if the path are the same', t => { 176 | let router = Router() 177 | const getHandler = () => t.pass('Handler called') 178 | const failHandler = () => t.fail('Wrong handler called') 179 | 180 | router.get('/get/something/here', failHandler) 181 | router.get('/get/something/there', getHandler) 182 | 183 | return router.route({ resourcePath: '/get/something/there', method: 'GET' }, {}) 184 | }) 185 | 186 | test('route matches on the method if the Regex matches', t => { 187 | let router = Router() 188 | const getHandler = () => t.pass('Handler called') 189 | const failHandler = () => t.fail('Wrong handler called') 190 | 191 | router.get('/get', failHandler) 192 | router.get('/get/{id}', getHandler) 193 | 194 | return router.route({ resourcePath: '/get/123jkhl1khj23123', method: 'GET' }, {}) 195 | }) 196 | 197 | test('route tokenizes path parts', t => { 198 | let router = Router() 199 | const getHandler = ({ pathParameters: { id } }) => { 200 | t.is(id, '123jkhl1khj23123', 'got tokenized id') 201 | } 202 | const failHandler = () => t.fail('Wrong handler called') 203 | 204 | router.get('/get', failHandler) 205 | router.get('/get/{id}', getHandler) 206 | 207 | return router.route({ resourcePath: '/get/123jkhl1khj23123', method: 'GET' }, {}) 208 | }) 209 | 210 | test('route does not tokenize without option', async t => { 211 | let router = Router({ extractPathParameters: false }) 212 | const getHandler = ({ pathParameters }) => { 213 | t.deepEqual(pathParameters, {}, 'no id') 214 | } 215 | const failHandler = () => t.fail('Wrong handler called') 216 | 217 | router.get('/get', failHandler) 218 | router.get('/get/{id}', getHandler) 219 | router.unknown(failHandler) 220 | 221 | return router.route( 222 | { 223 | pathParameters: {}, 224 | resourcePath: '/get/123jkhl1khj23123', 225 | method: 'GET' 226 | }, 227 | {} 228 | ) 229 | }) 230 | 231 | test('if the handler throws an error, the router returns it', async t => { 232 | let router = Router() 233 | router.debug = true 234 | 235 | const getHandler = () => { 236 | throw new Error('testing an error') 237 | } 238 | 239 | router.get('/get', getHandler) 240 | 241 | let result = await router.route({ resourcePath: '/get', method: 'GET' }, {}) 242 | 243 | t.falsy(result.isOk, 'resposne is error') 244 | t.is(result.response.statusCode, 500, 'status code') 245 | t.truthy( 246 | JSON.parse(result.response.body).message.indexOf('testing an error') !== -1, 247 | 'The proper error bubbled up.' 248 | ) 249 | }) 250 | 251 | test('if the handler throws an error, the router formats it', async t => { 252 | let router = Router() 253 | router.debug = true 254 | 255 | router.get('/get', () => { 256 | throw new Error('testing an error') 257 | }) 258 | 259 | router.formatError((statusCode, error) => { 260 | error.customProp = 'formatted' 261 | return error 262 | }) 263 | 264 | let result = await router.route({ resourcePath: '/get', method: 'GET' }, {}) 265 | 266 | t.falsy(result.isOk, 'resposne is error') 267 | t.is(result.response.statusCode, 500, 'status code') 268 | t.is(JSON.parse(result.response.body).customProp, 'formatted', 'custom formatting applied') 269 | }) 270 | 271 | test('if no route is defined the default router returns an error', async t => { 272 | let router = Router() 273 | let result = await router.route({ resourcePath: '/none', method: 'GET' }, {}) 274 | t.truthy( 275 | JSON.parse(result.response.body).message.includes('Endpoint not supported'), 276 | 'The proper error bubbled up.' 277 | ) 278 | }) 279 | 280 | test('route throws if context.response has already been set', async t => { 281 | t.plan(1) 282 | let router = Router() 283 | router.post('/route', () => {}) 284 | await router.route({}, { response: true }, '/route', 'POST').catch(err => { 285 | t.truthy(err.message.includes('context.response'), 'already set') 286 | }) 287 | }) 288 | 289 | test('route allows custom response status codes', async t => { 290 | t.plan(1) 291 | let router = Router() 292 | router.post('/route', (_, { response }) => response(201, 'nothing')) 293 | let result = await router.route({}, {}, '/route', 'POST') 294 | t.is(result.response.statusCode, 201, 'custom code') 295 | }) 296 | 297 | test('route allows custom response headers', async t => { 298 | t.plan(3) 299 | let router = Router() 300 | router.post('/route', (_, { response }) => { 301 | response.setHeader('Location', 'something') 302 | return { message: 'success' } 303 | }) 304 | let result = await router.route({}, {}, '/route', 'POST') 305 | t.is(result.response.statusCode, 200, 'status code') 306 | t.is(result.response.body, JSON.stringify({ message: 'success' }), 'body') 307 | t.is(result.response.headers.Location, 'something', 'custom header') 308 | }) 309 | 310 | test('route errors still format when using custom response headers', async t => { 311 | let router = Router() 312 | router.debug = true 313 | 314 | router.get('/get', (_, { response }) => { 315 | response.setHeader('Location', 'something') 316 | throw new Error('testing an error') 317 | }) 318 | 319 | router.formatError((statusCode, error) => { 320 | error.customProp = 'formatted' 321 | return error 322 | }) 323 | 324 | let result = await router.route({ resourcePath: '/get', method: 'GET' }, {}) 325 | t.is(result.response.headers.Location, 'something', 'custom header') 326 | }) 327 | 328 | test('route parses json body with default option', async t => { 329 | t.plan(1) 330 | let router = Router() 331 | router.post('/route', ({ body }) => { 332 | t.is(body.name, 'tim', 'parsed') 333 | }) 334 | await router.route( 335 | { 336 | body: JSON.stringify({ name: 'tim' }), 337 | headers: { 'Content-Type': 'application/json' } 338 | }, 339 | {}, 340 | '/route', 341 | 'POST' 342 | ) 343 | }) 344 | 345 | test('route parses json body with assumeJson', async t => { 346 | t.plan(1) 347 | let router = Router({ assumeJson: true }) 348 | router.post('/route', ({ body }) => { 349 | t.is(body.name, 'tim', 'parsed') 350 | }) 351 | await router.route( 352 | { 353 | body: JSON.stringify({ name: 'tim' }) 354 | }, 355 | {}, 356 | '/route', 357 | 'POST' 358 | ) 359 | }) 360 | 361 | test('route parses url-encoded body with default option', async t => { 362 | t.plan(1) 363 | let router = Router() 364 | router.post('/route', ({ body }) => { 365 | t.is(body.name, 'tim', 'parsed') 366 | }) 367 | await router.route( 368 | { 369 | body: qs.stringify({ name: 'tim' }), 370 | headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 371 | }, 372 | {}, 373 | '/route', 374 | 'POST' 375 | ) 376 | }) 377 | 378 | test('route parses url-encoded body with multi-typed content header', async t => { 379 | t.plan(1) 380 | let router = Router() 381 | router.post('/route', ({ body }) => { 382 | t.is(body.name, 'tim', 'parsed') 383 | }) 384 | await router.route( 385 | { 386 | body: qs.stringify({ name: 'tim' }), 387 | headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } 388 | }, 389 | {}, 390 | '/route', 391 | 'POST' 392 | ) 393 | }) 394 | 395 | test('route returns 400 for parse errors', async t => { 396 | t.plan(1) 397 | let router = Router() 398 | router.post('/route', ({ body }) => {}) 399 | let result = await router.route( 400 | { body: 'name', headers: { 'Content-Type': 'application/json' } }, 401 | {}, 402 | '/route', 403 | 'POST' 404 | ) 405 | t.is(result.response.statusCode, 400) 406 | }) 407 | 408 | test('route does not parse body with option', async t => { 409 | t.plan(1) 410 | let router = Router({ parseBody: false }) 411 | router.post('/route', ({ body }) => { 412 | t.is(body, JSON.stringify({ name: 'tim' }), 'parsed') 413 | }) 414 | await router.route( 415 | { 416 | body: JSON.stringify({ name: 'tim' }), 417 | headers: { 'Content-Type': 'application/json' } 418 | }, 419 | {}, 420 | '/route', 421 | 'POST' 422 | ) 423 | }) 424 | 425 | test('route decodes parameters with default option', async t => { 426 | t.plan(2) 427 | let router = Router() 428 | router.post('/route', ({ pathParameters, queryStringParameters }) => { 429 | t.is(pathParameters.name, 'tim kye', 'parsed') 430 | t.is(queryStringParameters.name, 'tim kye', 'parsed') 431 | }) 432 | await router.route( 433 | { 434 | pathParameters: { name: 'tim%20kye' }, 435 | queryStringParameters: { name: 'tim%20kye' } 436 | }, 437 | {}, 438 | '/route', 439 | 'POST' 440 | ) 441 | }) 442 | 443 | test('route does not decode parameters with option', async t => { 444 | t.plan(2) 445 | let router = Router({ decodeEvent: false }) 446 | router.post('/route', ({ pathParameters, queryStringParameters }) => { 447 | t.is(pathParameters.name, 'tim%20kye', 'parsed') 448 | t.is(queryStringParameters.name, 'tim%20kye', 'parsed') 449 | }) 450 | await router.route( 451 | { 452 | pathParameters: { name: 'tim%20kye' }, 453 | queryStringParameters: { name: 'tim%20kye' } 454 | }, 455 | {}, 456 | '/route', 457 | 'POST' 458 | ) 459 | }) 460 | 461 | test('traceId is created', async t => { 462 | t.plan(1) 463 | let router = Router() 464 | router.post('/route', () => {}) 465 | let result = await router.route({}, {}, '/route', 'POST') 466 | t.truthy( 467 | result.response.headers['X-Correlation-Id'], 468 | 'trace id ' + result.response.headers['X-Correlation-Id'] 469 | ) 470 | }) 471 | 472 | test('traceId is skipped if disabled', async t => { 473 | t.plan(1) 474 | let router = Router({ includeTraceId: false }) 475 | router.post('/route', () => {}) 476 | let result = await router.route({}, {}, '/route', 'POST') 477 | t.falsy(result.response.headers['X-Correlation-Id'], 'no trace id') 478 | }) 479 | 480 | test('traceId is reused from event', async t => { 481 | t.plan(6) 482 | let router = Router() 483 | router.post('/route', () => {}) 484 | let traceId = '1234' 485 | let result = await router.route({ headers: { 'X-Trace-Id': traceId } }, {}, '/route', 'POST') 486 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 487 | 488 | result = await router.route({ headers: { 'X-TRACE-ID': traceId } }, {}, '/route', 'POST') 489 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 490 | 491 | result = await router.route({ headers: { 'x-trace-id': traceId } }, {}, '/route', 'POST') 492 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 493 | 494 | result = await router.route({ headers: { 'X-Correlation-Id': traceId } }, {}, '/route', 'POST') 495 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 496 | 497 | result = await router.route({ headers: { 'X-CORRELATION-ID': traceId } }, {}, '/route', 'POST') 498 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 499 | 500 | result = await router.route({ headers: { 'x-correlation-id': traceId } }, {}, '/route', 'POST') 501 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 502 | }) 503 | 504 | test('traceId is reused from context', async t => { 505 | t.plan(1) 506 | let router = Router() 507 | router.post('/route', () => {}) 508 | let traceId = '1234' 509 | let result = await router.route({ headers: {} }, { awsRequestId: traceId }, '/route', 'POST') 510 | t.is(result.response.headers['X-Correlation-Id'], traceId, 'trace id ') 511 | }) 512 | 513 | test('context getters work inside routes', async t => { 514 | t.plan(1) 515 | let router = Router() 516 | router.post('/route', (event, { name }) => { 517 | t.is(name, 'tim', 'context prop passed in') 518 | }) 519 | let context = {} 520 | Object.defineProperty(context, 'name', { 521 | enumerable: false, 522 | configurable: false, 523 | get: () => 'tim' 524 | }) 525 | await router.route({}, context, '/route', 'POST') 526 | }) 527 | 528 | test('middleware is called', async t => { 529 | t.plan(1) 530 | 531 | let beforeRouteStub = sinon.stub() 532 | let lambdaEvent = {} 533 | let context = {} 534 | let path = '/route' 535 | let method = 'GET' 536 | let router = Router() 537 | 538 | router.beforeRoute(beforeRouteStub) 539 | router.get(path, sinon.stub()) 540 | 541 | await router.route(lambdaEvent, context, path, method) 542 | 543 | t.truthy( 544 | beforeRouteStub.calledWith(lambdaEvent, context, path, method), 545 | 'function was called with event, context, path, method' 546 | ) 547 | }) 548 | 549 | test('throwing an error in middleware creates error response', async t => { 550 | t.plan(2) 551 | 552 | let beforeRouteStub = () => { 553 | const error = new Error() 554 | error.statusCode = 400 555 | throw error 556 | } 557 | let path = '/route' 558 | let router = Router() 559 | let routeHandler = sinon.stub() 560 | 561 | router.beforeRoute(beforeRouteStub) 562 | router.get(path, routeHandler) 563 | 564 | const result = await router.route({}, {}, path, 'GET') 565 | 566 | t.is(result.response.statusCode, 400, 'includes 400 statusCode') 567 | 568 | t.truthy(routeHandler.notCalled, 'route handler was not called') 569 | }) 570 | 571 | test('multiple middleware functions are accepted', async t => { 572 | t.plan(2) 573 | 574 | let middlewareA = sinon.stub() 575 | let middlewareB = sinon.stub() 576 | let path = '/route' 577 | let router = Router() 578 | 579 | router.beforeRoute(middlewareA) 580 | router.beforeRoute(middlewareB) 581 | router.get(path, sinon.stub()) 582 | 583 | await router.route({}, {}, path, 'GET') 584 | 585 | t.truthy(middlewareA.called, 'first middleware was called') 586 | t.truthy(middlewareB.called, 'second middleware was called') 587 | }) 588 | 589 | test('middleware can be asynchronous', async t => { 590 | t.plan(1) 591 | 592 | let error = new Error('hello') 593 | error.statusCode = 400 594 | 595 | let beforeRouteStub = sinon.stub().rejects(error) 596 | let router = Router() 597 | let path = '/route' 598 | 599 | router.beforeRoute(beforeRouteStub) 600 | router.get(path, sinon.stub()) 601 | 602 | const result = await router.route({}, {}, path, 'GET') 603 | 604 | t.is(result.response.statusCode, 400, 'includes 400 statusCode') 605 | }) 606 | 607 | test('route does not normalize headers by default', async t => { 608 | t.plan(2) 609 | let router = Router({}) 610 | router.post('/route', ({ headers: { 'Content-Type': unnormal, 'content-type': normal } }) => { 611 | t.is(unnormal, 'application/json', 'unnormalized') 612 | t.is(normal, undefined, 'normalized') 613 | }) 614 | await router.route( 615 | { 616 | body: JSON.stringify({ name: 'tim' }), 617 | headers: { 'Content-Type': 'application/json' } 618 | }, 619 | {}, 620 | '/route', 621 | 'POST' 622 | ) 623 | }) 624 | 625 | test('route normalizes headers with an option', async t => { 626 | t.plan(2) 627 | let router = Router({ normalizeHeaders: true }) 628 | router.post('/route', ({ headers: { 'Content-Type': unnormal, 'content-type': normal } }) => { 629 | t.is(normal, 'application/json', 'normalized') 630 | t.is(unnormal, undefined, 'unnormalized') 631 | }) 632 | await router.route( 633 | { 634 | body: JSON.stringify({ name: 'tim' }), 635 | headers: { 'Content-Type': 'application/json' } 636 | }, 637 | {}, 638 | '/route', 639 | 'POST' 640 | ) 641 | }) 642 | 643 | test('pass original error props on formatError', async t => { 644 | t.plan(3) 645 | const router = Router() 646 | const errorName = 'ValidationError' 647 | const errorMessage = 'Ops, validation error' 648 | 649 | router.post('/route', (event, { name }) => { 650 | const error = new Error(errorMessage) 651 | error.name = errorName 652 | throw error 653 | }) 654 | 655 | router.formatError((statusCode, error) => { 656 | t.is(statusCode, 500) 657 | t.is(error.message, errorMessage) 658 | t.is(error.name, errorName) 659 | }) 660 | 661 | await router.route({}, {}, '/route', 'POST') 662 | }) 663 | --------------------------------------------------------------------------------