├── .gitignore ├── LICENSE ├── README.md ├── apis └── helloworld │ ├── functions │ └── greeting │ │ ├── .eslintrc │ │ ├── .prettierrc │ │ ├── jest.config.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── src │ │ ├── __tests__ │ │ │ └── handler.test.ts │ │ └── handler.ts │ │ ├── tsconfig.json │ │ └── webpack.config.ts │ ├── layers │ ├── api-responses │ │ ├── .eslintrc │ │ ├── .prettierrc │ │ ├── jest.config.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── src │ │ │ ├── __tests__ │ │ │ │ └── defaultResponses.test.ts │ │ │ └── defaultResponses.ts │ │ ├── tsconfig.json │ │ └── webpack.config.ts │ └── global-dependencies │ │ └── package.json │ └── template.yaml └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/osx,node,linux,windows 2 | 3 | # -------------------------------------------------- 4 | # Linux 5 | # -------------------------------------------------- 6 | 7 | *~ 8 | 9 | # temporary files which can be created if a process still has a handle open of a deleted file 10 | .fuse_hidden* 11 | 12 | # KDE directory preferences 13 | .directory 14 | 15 | # Linux trash folder which might appear on any partition or disk 16 | .Trash-* 17 | 18 | # .nfs files are created when an open file is removed but is still being accessed 19 | .nfs* 20 | 21 | # -------------------------------------------------- 22 | # OSX Mac 23 | # -------------------------------------------------- 24 | 25 | *.DS_Store 26 | .AppleDouble 27 | .LSOverride 28 | 29 | # Icon must end with two \r 30 | Icon 31 | 32 | # Thumbnails 33 | ._* 34 | 35 | # Files that might appear in the root of a volume 36 | .DocumentRevisions-V100 37 | .fseventsd 38 | .Spotlight-V100 39 | .TemporaryItems 40 | .Trashes 41 | .VolumeIcon.icns 42 | .com.apple.timemachine.donotpresent 43 | 44 | # Directories potentially created on remote AFP share 45 | .AppleDB 46 | .AppleDesktop 47 | Network Trash Folder 48 | Temporary Items 49 | .apdisk 50 | 51 | # -------------------------------------------------- 52 | # Windows 53 | # -------------------------------------------------- 54 | 55 | # Windows thumbnail cache files 56 | Thumbs.db 57 | ehthumbs.db 58 | ehthumbs_vista.db 59 | 60 | # Folder config file 61 | Desktop.ini 62 | 63 | # Recycle Bin used on file shares 64 | $RECYCLE.BIN/ 65 | 66 | # Windows Installer files 67 | *.cab 68 | *.msi 69 | *.msm 70 | *.msp 71 | 72 | # Windows shortcuts 73 | *.lnk 74 | 75 | # -------------------------------------------------- 76 | # Node 77 | # -------------------------------------------------- 78 | 79 | # Logs 80 | logs 81 | *.log 82 | npm-debug.log* 83 | yarn-debug.log* 84 | yarn-error.log* 85 | 86 | # Runtime data 87 | pids 88 | *.pid 89 | *.seed 90 | *.pid.lock 91 | 92 | # Directory for instrumented libs generated by jscoverage/JSCover 93 | lib-cov 94 | 95 | # Coverage directory used by tools like istanbul 96 | coverage 97 | 98 | # nyc test coverage 99 | .nyc_output 100 | 101 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 102 | .grunt 103 | 104 | # Bower dependency directory (https://bower.io/) 105 | bower_components 106 | 107 | # node-waf configuration 108 | .lock-wscript 109 | 110 | # Compiled binary addons (http://nodejs.org/api/addons.html) 111 | build/Release 112 | 113 | # Dependency directories 114 | node_modules/ 115 | jspm_packages/ 116 | 117 | # Test Coverage 118 | coverage/ 119 | 120 | # Production Build Code 121 | dist/ 122 | 123 | # Typescript v1 declaration files 124 | typings/ 125 | 126 | # Optional npm cache directory 127 | .npm 128 | 129 | # Optional eslint cache 130 | .eslintcache 131 | 132 | # Optional REPL history 133 | .node_repl_history 134 | 135 | # Output of 'npm pack' 136 | *.tgz 137 | 138 | # Yarn Integrity file 139 | .yarn-integrity 140 | 141 | # dotenv environment variables file 142 | .env 143 | 144 | # -------------------------------------------------- 145 | # Application 146 | # -------------------------------------------------- 147 | 148 | # SAM Configuration 149 | .aws-sam/ 150 | 151 | # Environment Variables 152 | env.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serverless-SAM-typscript-boilerplate 2 | A boilerplate AWS SAM template using Typescript and Layers 3 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { 4 | "es2020": true, 5 | "mongo": true, 6 | "node": true, 7 | "jest": true 8 | }, 9 | "parser": "@typescript-eslint/parser", 10 | "extends": [ 11 | "plugin:@typescript-eslint/recommended", 12 | "plugin:prettier/recommended" // This will display prettier errors as ESLint errors. Make sure this is always the last configuration. 13 | ], 14 | "ignorePatterns": ["dist/", "coverage/", "test/"], 15 | "parserOptions": { 16 | "ecmaVersion": 2018, 17 | "sourceType": "module", 18 | "ecmaFeatures": { 19 | "impliedStrict": true 20 | } 21 | }, 22 | "rules": { 23 | "max-len": [ 24 | "error", 25 | { 26 | "code": 100, 27 | "ignoreComments": true, 28 | "ignoreStrings": true, 29 | "ignoreTemplateLiterals": true 30 | } 31 | ], 32 | "quotes": ["error", "single", { "allowTemplateLiterals": true }], 33 | "no-unused-vars": "off", 34 | "@typescript-eslint/no-unused-vars": [ 35 | "error", 36 | { 37 | "vars": "all", 38 | "args": "none" 39 | } 40 | ] 41 | }, 42 | "settings": { 43 | "import/resolver": { 44 | "node": { 45 | "extensions": [".js", ".jsx", ".ts", ".tsx"] 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/jest.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | const { pathsToModuleNameMapper } = require('ts-jest/utils'); 3 | const { compilerOptions } = require('./tsconfig.json'); 4 | /* eslint-enable */ 5 | 6 | module.exports = { 7 | preset: 'ts-jest', 8 | moduleFileExtensions: ['ts', 'js'], 9 | moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { 10 | prefix: '', 11 | }), 12 | transform: { 13 | '^.+\\.(ts|tsx)$': 'ts-jest', 14 | }, 15 | testMatch: ['**/__tests__/**/*.[jt]s?(x)'], 16 | testPathIgnorePatterns: ['dist/'], 17 | testEnvironment: 'node', 18 | }; 19 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "greeting-function", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "build:dev": "npm run clean && mkdir ./dist && cp package.json ./dist/package.json && webpack -w", 6 | "build:prod": "npm run clean && mkdir ./dist && cp package.json ./dist/package.json && NODE_ENV=${NODE_ENV:-production} webpack", 7 | "clean": "rm -rf dist/", 8 | "test": "jest" 9 | }, 10 | "devDependencies": { 11 | "@types/aws-lambda": "^8.10.59", 12 | "@types/jest": "^26.0.5", 13 | "@types/node": "^14.0.23", 14 | "@types/webpack": "^4.41.21", 15 | "@typescript-eslint/eslint-plugin": "^3.6.0", 16 | "@typescript-eslint/parser": "^3.6.0", 17 | "eslint": "^7.4.0", 18 | "eslint-config-prettier": "^6.10.1", 19 | "eslint-plugin-import": "^2.20.2", 20 | "eslint-plugin-prettier": "^3.1.2", 21 | "jest": "^26.1.0", 22 | "prettier": "^2.0.5", 23 | "ts-jest": "^26.1.3", 24 | "ts-loader": "^8.0.1", 25 | "ts-node": "^8.10.2", 26 | "typescript": "^3.9.7", 27 | "webpack": "^4.7.0", 28 | "webpack-cli": "^3.1.1", 29 | "yaml-cfn": "^0.2.3" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/src/__tests__/handler.test.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayProxyEvent } from 'aws-lambda'; 2 | 3 | import handler from '../handler'; 4 | 5 | let mockEvent: APIGatewayProxyEvent; 6 | 7 | beforeEach(() => { 8 | /** Create a mock event body */ 9 | mockEvent = ({ 10 | body: JSON.stringify({ 11 | firstName: `John`, 12 | lastName: `Doe`, 13 | email: `jdoe@gmail.com`, 14 | password: `Abcd1234`, 15 | }), 16 | } as unknown) as APIGatewayProxyEvent; 17 | }); 18 | 19 | test(`Should return hello world response`, async (done) => { 20 | const expectedResponse = { 21 | statusCode: 200, 22 | headers: { 23 | 'Content-Type': 'application/json', 24 | }, 25 | body: JSON.stringify({ error: {}, data: { message: 'Hello World!' } }), 26 | }; 27 | 28 | const result = await handler(mockEvent); 29 | 30 | expect(result).toEqual(expectedResponse); 31 | done(); 32 | }); 33 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/src/handler.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; 2 | 3 | import response from '/opt/nodejs/defaultResponses'; 4 | 5 | export default async (event: APIGatewayProxyEvent): Promise => { 6 | return Promise.resolve(response.success(200, {}, { message: 'Hello World!' })); 7 | }; 8 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "esModuleInterop": true, 5 | "target": "esnext", 6 | "noImplicitAny": true, 7 | "moduleResolution": "node", 8 | "sourceMap": true, 9 | "baseUrl": ".", 10 | "paths": { 11 | "/opt/nodejs/defaultResponses": ["../../layers/api-responses/src/defaultResponses"] 12 | } 13 | }, 14 | "include": ["./**/*"] 15 | } 16 | -------------------------------------------------------------------------------- /apis/helloworld/functions/greeting/webpack.config.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path'; 2 | import { readFileSync } from 'fs'; 3 | import { yamlParse } from 'yaml-cfn'; 4 | import { Configuration } from 'webpack'; 5 | 6 | /* eslint-disable */ 7 | const { compilerOptions } = require('./tsconfig.json'); 8 | /* eslint-enable */ 9 | 10 | /** Webpack Config Variables */ 11 | const conf = { 12 | prodMode: process.env.NODE_ENV === 'production', 13 | templatePath: '../../template.yaml', 14 | }; 15 | 16 | /** 17 | * Parsing tsconfig.json paths to resolve aliases 18 | */ 19 | const tsPaths = Object.keys(compilerOptions.paths).reduce( 20 | (paths, path) => 21 | Object.assign(paths, { [`${path}`]: resolve(__dirname, compilerOptions.paths[path][0]) }), 22 | {} 23 | ); 24 | 25 | /** 26 | * Parsing template.yaml file for function dir locations 27 | */ 28 | 29 | /** Interface for AWS SAM Function */ 30 | interface ISamFunction { 31 | Type: string; 32 | Properties: { 33 | AssumeRolePolicyDocument?: JSON; 34 | AutoPublishAlias?: string; 35 | AutoPublishCodeSha256?: string; 36 | CodeUri?: string; 37 | Description?: string; 38 | Environment?: { 39 | Variables: { 40 | [key: string]: string; 41 | }; 42 | }; 43 | Events?: EventSource; 44 | FunctionName?: string; 45 | Handler: string; 46 | Layers?: { [Ref: string]: string }[]; 47 | Runtime: string; 48 | Timeout?: number; 49 | Tracing?: string; 50 | VersionDescription?: string; 51 | }; 52 | } 53 | 54 | const { resources } = yamlParse(readFileSync(conf.templatePath, 'utf-8')); 55 | 56 | const entries = Object.values(resources) 57 | 58 | .filter((resource: ISamFunction) => resource.Type === 'AWS::Serverless::Function') 59 | 60 | .filter( 61 | (resource: ISamFunction) => 62 | resource.Properties.Runtime && resource.Properties.Runtime.startsWith('nodejs') 63 | ) 64 | 65 | .map((resource: ISamFunction) => ({ 66 | filename: resource.Properties.Handler.split('.')[0], 67 | entryPath: resource.Properties.CodeUri.split('/').splice(3).join('/'), 68 | })) 69 | 70 | .reduce( 71 | (resources, resource) => 72 | Object.assign(resources, { 73 | [`${resource.filename}`]: `./src/${resource.entryPath}${resource.filename}.ts`, 74 | }), 75 | {} 76 | ); 77 | 78 | /** 79 | * Webpack Config 80 | */ 81 | const webpackConfig: Configuration = { 82 | entry: entries, 83 | target: 'node', 84 | mode: conf.prodMode ? 'production' : 'development', 85 | module: { 86 | rules: [ 87 | { 88 | test: /\.tsx?$/, 89 | use: 'ts-loader', 90 | }, 91 | ], 92 | }, 93 | resolve: { 94 | extensions: ['.tsx', '.ts', '.js'], 95 | alias: tsPaths, 96 | }, 97 | output: { 98 | path: resolve(__dirname, 'dist'), 99 | filename: '[name].js', 100 | libraryTarget: 'commonjs2', 101 | }, 102 | devtool: 'source-map', 103 | plugins: [], 104 | }; 105 | 106 | export default webpackConfig; 107 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { 4 | "es2020": true, 5 | "mongo": true, 6 | "node": true, 7 | "jest": true 8 | }, 9 | "parser": "@typescript-eslint/parser", 10 | "extends": [ 11 | "airbnb", 12 | "plugin:@typescript-eslint/recommended", 13 | "plugin:prettier/recommended" // This will display prettier errors as ESLint errors. Make sure this is always the last configuration. 14 | ], 15 | "ignorePatterns": ["dist/", "coverage/", "test/"], 16 | "parserOptions": { 17 | "ecmaVersion": 2018, 18 | "sourceType": "module", 19 | "ecmaFeatures": { 20 | "impliedStrict": true 21 | } 22 | }, 23 | "rules": { 24 | "max-len": [ 25 | "error", 26 | { 27 | "code": 100, 28 | "ignoreComments": true, 29 | "ignoreStrings": true, 30 | "ignoreTemplateLiterals": true 31 | } 32 | ], 33 | "quotes": ["error", "single", { "allowTemplateLiterals": true }], 34 | "no-unused-vars": "off", 35 | "@typescript-eslint/no-unused-vars": [ 36 | "error", 37 | { 38 | "vars": "all", 39 | "args": "none" 40 | } 41 | ] 42 | }, 43 | "settings": { 44 | "import/resolver": { 45 | "node": { 46 | "extensions": [".js", ".jsx", ".ts", ".tsx"] 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | globals: { 3 | 'ts-jest': { 4 | tsConfig: 'tsconfig.json', 5 | }, 6 | }, 7 | moduleFileExtensions: ['ts', 'js'], 8 | transform: { 9 | '^.+\\.(ts|tsx)$': 'ts-jest', 10 | }, 11 | testMatch: ['**/__tests__/**/*.[jt]s?(x)'], 12 | testPathIgnorePatterns: ['dist/'], 13 | testEnvironment: 'node', 14 | }; 15 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-responses-layer", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "build:dev": "npm run clean && mkdir ./dist && cp package.json ./dist/package.json && webpack -w", 6 | "build:prod": "npm run clean && mkdir ./dist && cp package.json ./dist/package.json && NODE_ENV=${NODE_ENV:-production} webpack", 7 | "clean": "rm -rf dist/", 8 | "test": "jest" 9 | }, 10 | "devDependencies": { 11 | "@types/aws-lambda": "^8.10.59", 12 | "@types/jest": "^26.0.5", 13 | "@types/node": "^14.0.23", 14 | "@types/webpack": "^4.41.21", 15 | "@typescript-eslint/eslint-plugin": "^3.6.0", 16 | "@typescript-eslint/parser": "^3.6.0", 17 | "eslint": "^7.4.0", 18 | "eslint-config-prettier": "^6.10.1", 19 | "eslint-plugin-import": "^2.20.2", 20 | "eslint-plugin-prettier": "^3.1.2", 21 | "jest": "^26.1.0", 22 | "prettier": "^2.0.5", 23 | "ts-jest": "^26.1.3", 24 | "ts-loader": "^8.0.1", 25 | "ts-node": "^8.10.2", 26 | "typescript": "^3.9.7", 27 | "webpack": "^4.7.0", 28 | "webpack-cli": "^3.1.1" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/src/__tests__/defaultResponses.test.ts: -------------------------------------------------------------------------------- 1 | import response from '../defaultResponses'; 2 | 3 | describe(`API Response Success Tests`, () => { 4 | test(`Should return a default response`, () => { 5 | const expectedResponse = { 6 | statusCode: 200, 7 | headers: { 8 | 'Content-Type': 'application/json', 9 | }, 10 | body: JSON.stringify({ 11 | error: {}, 12 | data: {}, 13 | }), 14 | }; 15 | 16 | const result = response.success(); 17 | 18 | expect(result.statusCode).toBe(200); 19 | expect(result).toEqual(expectedResponse); 20 | }); 21 | 22 | test(`Should return custom headers`, () => { 23 | const headerParam = { 24 | 'Custom Header': '1234', 25 | }; 26 | 27 | const result = response.success(204, headerParam); 28 | 29 | expect(result.headers).toHaveProperty('Custom Header', headerParam['Custom Header']); 30 | }); 31 | 32 | test(`Should return 204 with no body`, () => { 33 | const expectedBody = JSON.stringify({}); 34 | 35 | const result = response.success(204); 36 | 37 | expect(result.statusCode).toBe(204); 38 | expect(result.body).toEqual(expectedBody); 39 | }); 40 | 41 | test(`Should return 200 with body data`, () => { 42 | const body = { 43 | userId: '1234', 44 | }; 45 | 46 | const expectedBody = JSON.stringify({ 47 | error: {}, 48 | data: body, 49 | }); 50 | 51 | const result = response.success(200, {}, body); 52 | 53 | expect(result.statusCode).toBe(200); 54 | expect(result.body).toEqual(expectedBody); 55 | }); 56 | }); 57 | 58 | describe(`API Response Error Tests`, () => { 59 | beforeEach(() => { 60 | console.log = jest.fn(); 61 | }); 62 | 63 | afterEach(() => { 64 | jest.clearAllMocks(); 65 | }); 66 | 67 | test(`Should return a default error`, () => { 68 | const expectedBody = JSON.stringify({ 69 | error: { 70 | message: 71 | 'There was an internal server error. Please try again later. If the problem persists, please contact technical support.', 72 | }, 73 | data: {}, 74 | }); 75 | 76 | const expectedResponse = { 77 | statusCode: 500, 78 | headers: { 79 | 'Content-Type': 'application/json', 80 | }, 81 | body: expectedBody, 82 | }; 83 | 84 | const result = response.error(); 85 | 86 | expect(result.statusCode).toBe(500); 87 | expect(result).toEqual(expectedResponse); 88 | }); 89 | 90 | test(`Should return custom headers`, () => { 91 | const headerParam = { 92 | 'Custom Header': '1234', 93 | }; 94 | 95 | const result = response.error(500, headerParam); 96 | 97 | expect(console.log).toHaveBeenCalledTimes(1); 98 | expect(result.statusCode).toBe(500); 99 | expect(result.headers).toHaveProperty('Custom Header', headerParam['Custom Header']); 100 | }); 101 | 102 | test(`Should return 500 error wtih general`, () => { 103 | const expectedBody = JSON.stringify({ 104 | error: { 105 | message: 106 | 'There was an internal server error. Please try again later. If the problem persists, please contact technical support.', 107 | }, 108 | data: {}, 109 | }); 110 | 111 | const result = response.error(500); 112 | 113 | expect(console.log).toHaveBeenCalledTimes(1); 114 | expect(result.statusCode).toBe(500); 115 | expect(result.body).toEqual(expectedBody); 116 | }); 117 | 118 | test(`Should return 400 error with message`, () => { 119 | const error = new Error('This was a bad request'); 120 | 121 | const expectedBody = JSON.stringify({ 122 | error: { 123 | message: error.message, 124 | }, 125 | data: {}, 126 | }); 127 | 128 | const result = response.error(400, {}, error); 129 | 130 | expect(console.log).toHaveBeenCalledTimes(1); 131 | expect(result.statusCode).toBe(400); 132 | expect(result.body).toEqual(expectedBody); 133 | }); 134 | }); 135 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/src/defaultResponses.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayProxyResult } from 'aws-lambda'; 2 | 3 | const response = { 4 | success: (statusCode: number = 200, headers: any = {}, data: any = {}): APIGatewayProxyResult => { 5 | /** Generate default response with no data */ 6 | const response: { 7 | statusCode: number; 8 | headers: any; 9 | body: any; 10 | } = { 11 | statusCode, 12 | headers: { 13 | 'Content-Type': 'application/json', 14 | ...headers, 15 | }, 16 | body: JSON.stringify({}), 17 | }; 18 | 19 | /** Add body if status is not 204 and there is data to add. */ 20 | if (statusCode !== 204) 21 | response.body = JSON.stringify({ 22 | error: {}, 23 | data, 24 | }); 25 | 26 | return response; 27 | }, 28 | error: (statusCode: number = 500, headers: any = {}, err?: Error): APIGatewayProxyResult => { 29 | /** Log the error */ 30 | console.log(err); 31 | 32 | /** Generate default response with no error */ 33 | const response: { 34 | statusCode: number; 35 | headers: any; 36 | body: any; 37 | } = { 38 | statusCode, 39 | headers: { 40 | 'Content-Type': 'application/json', 41 | ...headers, 42 | }, 43 | body: JSON.stringify({ 44 | error: {}, 45 | data: {}, 46 | }), 47 | }; 48 | 49 | /** If status code is 500, return a general internal server error */ 50 | if (statusCode === 500) { 51 | response.body = JSON.stringify({ 52 | error: { 53 | message: 54 | 'There was an internal server error. Please try again later. If the problem persists, please contact technical support.', 55 | }, 56 | data: {}, 57 | }); 58 | } 59 | 60 | /** If status code is not 500 and there is an error message, return it */ 61 | if (statusCode !== 500 && err.message) { 62 | response.body = JSON.stringify({ 63 | error: { 64 | message: err.message, 65 | }, 66 | data: {}, 67 | }); 68 | } 69 | 70 | return response; 71 | }, 72 | }; 73 | 74 | export default response; 75 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "esModuleInterop": true, 5 | "target": "esnext", 6 | "noImplicitAny": true, 7 | "moduleResolution": "node", 8 | "sourceMap": true 9 | }, 10 | "include": ["src/**/*"] 11 | } 12 | -------------------------------------------------------------------------------- /apis/helloworld/layers/api-responses/webpack.config.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path'; 2 | import { Configuration } from 'webpack'; 3 | 4 | const conf = { 5 | prodMode: process.env.NODE_ENV === 'production', 6 | templatePath: './template.yaml', 7 | }; 8 | 9 | const config: Configuration = { 10 | entry: { 11 | defaultApiResponses: resolve(__dirname, 'src', 'defaultResponses.ts'), 12 | }, 13 | target: 'node', 14 | mode: conf.prodMode ? 'production' : 'development', 15 | module: { 16 | rules: [ 17 | { 18 | test: /\.tsx?$/, 19 | use: 'ts-loader', 20 | }, 21 | ], 22 | }, 23 | resolve: { 24 | extensions: ['.tsx', '.ts', '.js'], 25 | }, 26 | output: { 27 | path: resolve(__dirname, 'dist'), 28 | filename: '[name].js', 29 | libraryTarget: 'commonjs2', 30 | }, 31 | devtool: 'source-map', 32 | plugins: [], 33 | }; 34 | 35 | export default config; 36 | -------------------------------------------------------------------------------- /apis/helloworld/layers/global-dependencies/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "global-dependencies-layer", 3 | "version": "1.0.0", 4 | "dependencies": {} 5 | } 6 | -------------------------------------------------------------------------------- /apis/helloworld/template.yaml: -------------------------------------------------------------------------------- 1 | # https://github.com/awslabs/serverless-application-model/blob/develop/versions/2016-10-31.md 2 | AWSTemplateFormatVersion: '2010-09-09' 3 | Transform: AWS::Serverless-2016-10-31 4 | Description: hellword-api 5 | 6 | Globals: 7 | Function: 8 | Timeout: 60 9 | 10 | Resources: 11 | GlobalDependenciesLayer: 12 | Type: AWS::Serverless::LayerVersion 13 | Properties: 14 | LayerName: GlobalDependenciesLayer 15 | ContentUri: layers/global-dependencies 16 | CompatibleRuntimes: 17 | - nodejs12.x 18 | RetentionPolicy: Retain 19 | Metadata: 20 | BuildMethod: nodejs12.x 21 | 22 | GlobalApiResponsesLayer: 23 | Type: AWS::Serverless::LayerVersion 24 | Properties: 25 | LayerName: GlobalApiResponsesLayer 26 | ContentUri: layers/api-responses/dist 27 | CompatibleRuntimes: 28 | - nodejs12.x 29 | RetentionPolicy: Retain 30 | Metadata: 31 | BuildMethod: nodejs12.x 32 | 33 | GreetingFunction: 34 | Type: AWS::Serverless::Function 35 | Properties: 36 | Handler: handler.default 37 | CodeUri: functions/greeting/dist 38 | Layers: 39 | - !Ref GlobalDependenciesLayer 40 | - !Ref GlobalApiResponsesLayer 41 | Runtime: nodejs12.x 42 | Events: 43 | Hello: 44 | Type: Api 45 | Properties: 46 | Path: /hello 47 | Method: get 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-sam-typscript-boilerplate", 3 | "version": "1.0.0", 4 | "description": "A boilerA boilerplate AWS SAM template using Typescript and Layers", 5 | "scripts": { 6 | "test": "echo \"Error: no test specified\" && exit 1" 7 | }, 8 | "repository": { 9 | "type": "git", 10 | "url": "git+https://github.com/Borduhh/serverless-SAM-typscript-boilerplate.git" 11 | }, 12 | "keywords": [ 13 | "AWS", 14 | "SAM", 15 | "serverless" 16 | ], 17 | "author": "Nick Bordeau", 18 | "license": "Apache-2.0", 19 | "bugs": { 20 | "url": "https://github.com/Borduhh/serverless-SAM-typscript-boilerplate/issues" 21 | }, 22 | "homepage": "https://github.com/Borduhh/serverless-SAM-typscript-boilerplate#readme" 23 | } 24 | --------------------------------------------------------------------------------