├── .build └── stack.json ├── .eslintrc.json ├── .gitignore ├── LICENSE ├── README.md ├── __tests__ ├── integration │ └── todos.test.js └── unit │ ├── listTodos.test.js │ └── postTodos.test.js ├── buildspec.yml ├── deploy.sh ├── package-lock.json ├── package.json ├── serverless.yml └── todos ├── handler.js └── todos.js /.build/stack.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServiceEndpoint": "http://localhost:3000" 3 | } 4 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base", 3 | "rules": { 4 | "no-console": 0, 5 | "comma-dangle": ["error", "never"], 6 | "arrow-body-style": ["error", "always"], 7 | "object-shorthand": ["error", "never"], 8 | "jest/no-disabled-tests": "warn", 9 | "jest/no-focused-tests": "error", 10 | "jest/no-identical-title": "error", 11 | "jest/prefer-to-have-length": "warn", 12 | "jest/valid-expect": "error" 13 | }, 14 | "plugins": [ 15 | "jest" 16 | ], 17 | "env": { 18 | "jest/globals": true 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # package directories 2 | node_modules 3 | jspm_packages 4 | 5 | # Serverless directories 6 | .serverless 7 | -------------------------------------------------------------------------------- /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 2017 1Strategy, LLC 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 CI/CD Tutorial 2 | ## Building, testing, and deploying Serverless apps using CodeBuild and CodePipeline 3 | 4 | This repo is the demo code for a [three-part tutorial](http://www.1strategy.com/blog/) on managing unit testing, integration testing, and deployment of apps built using the Serverless framework. 5 | 6 | To play with this code locally, clone this repo and do the following: 7 | 8 | ### 1. Install global npm modules 9 | ``` 10 | npm install -g serverless eslint jest 11 | ``` 12 | 13 | ### 2. Install local npm modules 14 | Navigate to the app directory, and run 15 | ``` 16 | npm install 17 | ``` 18 | ### 3. Bring up the DB 19 | ``` 20 | sls dynamodb install --stage dev 21 | sls dynamodb start --stage dev 22 | sls dynamodb migrate --stage dev 23 | ``` 24 | This series of commands installs a local DynamoDB, starts it, and creates any tables specified in the `serverless.yml`. Check your shell at [http://localhost:8000/shell/](http://localhost:8000/shell/) to interact with the db and view the created table. 25 | 26 | ### 4. Start the offline app 27 | ``` 28 | sls offline start --stage dev 29 | ``` 30 | 31 | The app is now available at `http://localhost:3000`. 32 | 33 | The app has two endpoints: 34 | 35 | #### GET /todos 36 | Returns a list of todos: 37 | ``` 38 | [ 39 | { 40 | "id": "9b3c415f-ceaa-49e3-b5af-0e335bfd4635", 41 | "completed": false, 42 | "title": "do things!", 43 | "updatedAt": 1513817875660 44 | } 45 | ] 46 | ``` 47 | 48 | #### POST /todos 49 | Accepts an object in this format: 50 | ``` 51 | { 52 | "title": "do things!", 53 | "completed": false 54 | } 55 | ``` 56 | Returns a status of 200. The created object is not returned; you can see it with a GET /todos. 57 | 58 | ### 5. Run Tests 59 | To run unit tests, use 60 | ``` 61 | npm test 62 | ``` 63 | 64 | To lint, use 65 | ``` 66 | npm run-script lint 67 | ``` 68 | 69 | To run integration tests, use 70 | ``` 71 | npm run-script integration 72 | ``` 73 | 74 | ### 6. Make Changes 75 | If you change the `serverless.yml` file, you'll need to restart your local app: 76 | - Stop the offline app; `ctrl-c` in the terminal where it's running is all you need. It's fine to leave the db running. 77 | - Uncomment the line in the `serverless.yml` file that says `noStart: true`. This will prevent serverless offline from trying to start a new database. 78 | - Run `sls offline start --stage dev` again. 79 | 80 | Changes to any other file in the app (e.g. a handler) will be reflected immediately, and don't require a restart. 81 | -------------------------------------------------------------------------------- /__tests__/integration/todos.test.js: -------------------------------------------------------------------------------- 1 | // use serverless-stack-output to find service endpoint 2 | const stackOutput = require('../../.build/stack.json'); 3 | 4 | const url = stackOutput.ServiceEndpoint; 5 | const request = require('supertest')(url); 6 | 7 | describe('/todos routes', () => { 8 | it('POST /todos returns an empty object', () => { 9 | const postObj = { 10 | title: 'Feed the cats', 11 | completed: false 12 | }; 13 | 14 | return request 15 | .post('/todos') 16 | .send(postObj) 17 | .expect(200) 18 | .then((res) => { 19 | expect(res).toBeDefined(); 20 | expect(res.body).toEqual({}); 21 | }); 22 | }); 23 | 24 | it('GET /todos returns a list with the previously posted todo', () => { 25 | request 26 | .get('/todos') 27 | .expect(200) 28 | .then((res) => { 29 | expect(res).toBeDefined(); 30 | expect(Array.isArray(res.body)).toBe(true); 31 | expect(res.body[0]).toHaveProperty('title', 'Feed the cats'); 32 | expect(res.body[0]).toHaveProperty('completed', false); 33 | expect(res.body[0]).toHaveProperty('id'); 34 | expect(res.body[0]).toHaveProperty('updatedAt'); 35 | }); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /__tests__/unit/listTodos.test.js: -------------------------------------------------------------------------------- 1 | const Todos = require('../../todos/todos.js'); 2 | 3 | describe('listTodos', () => { 4 | // mock the db 5 | const dbMock = {}; 6 | dbMock.scan = jest 7 | .fn((params, callback) => { 8 | callback(null, { Items: [] }); 9 | }) 10 | .mockName('db.scan'); 11 | 12 | // create new instance of todos with fake db 13 | const todos = new Todos(dbMock, 'Todos-fakeStage'); 14 | 15 | it('Calls the scan method once', () => { 16 | todos.list(() => { }); 17 | 18 | expect(dbMock.scan.mock.calls).toHaveLength(1); 19 | }); 20 | 21 | it('Calls the scan method with the correct arguments', () => { 22 | todos.list(() => { }); 23 | 24 | expect(dbMock.scan.mock.calls[0][0]).toEqual({ TableName: 'Todos-fakeStage' }); 25 | expect(dbMock.scan.mock.calls[1][0]).toBeTruthy(); 26 | }); 27 | 28 | it('Receives a response with status 200', () => { 29 | todos.list((err, res) => { 30 | expect(res.statusCode).toBe(200); 31 | }); 32 | }); 33 | 34 | it('Receives a response with the correct body', () => { 35 | todos.list((err, res) => { 36 | const parsedBody = JSON.parse(res.body); 37 | expect(parsedBody).toEqual([]); 38 | }); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /__tests__/unit/postTodos.test.js: -------------------------------------------------------------------------------- 1 | const Todos = require('../../todos/todos.js'); 2 | 3 | describe('postTodos', () => { 4 | // mock the db 5 | const dbMock = {}; 6 | dbMock.put = jest 7 | .fn((params, callback) => { 8 | callback(null, {}); 9 | }) 10 | .mockName('db.put'); 11 | 12 | // create new instance of todos with fake db 13 | const todos = new Todos(dbMock, 'Todos-fakeStage'); 14 | 15 | const postObj = { 16 | title: 'Feed the cat', 17 | completed: false 18 | }; 19 | 20 | it('Calls the put method once', () => { 21 | todos.post(postObj, () => {}); 22 | 23 | expect(dbMock.put.mock.calls).toHaveLength(1); 24 | }); 25 | 26 | it('Calls the put method with the correct arguments', () => { 27 | todos.post(postObj, () => {}); 28 | 29 | expect(dbMock.put.mock.calls[0][0].TableName).toBe('Todos-fakeStage'); 30 | expect(dbMock.put.mock.calls[1][0].Item).toHaveProperty('title', 'Feed the cat'); 31 | expect(dbMock.put.mock.calls[1][0].Item).toHaveProperty('completed', false); 32 | expect(dbMock.put.mock.calls[1][0].Item).toHaveProperty('id'); 33 | expect(dbMock.put.mock.calls[1][0].Item).toHaveProperty('updatedAt'); 34 | }); 35 | 36 | it('Receives a response with status 200', () => { 37 | todos.post(postObj, (err, res) => { 38 | expect(res.statusCode).toBe(200); 39 | }); 40 | }); 41 | 42 | it('Receives an empty object in the body', () => { 43 | todos.post(postObj, (err, res) => { 44 | const parsedBody = JSON.parse(res.body); 45 | expect(parsedBody).toEqual({}); 46 | }); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | phases: 4 | install: 5 | runtime-versions: 6 | nodejs: 10 7 | commands: 8 | # remove package-lock before updating npm, otherwise not all dependencies will install 9 | - rm package-lock.json 10 | # update npm to 5.6.0 due to package-lock bug: https://github.com/npm/npm/issues/18135 11 | - npm install --silent --progress=false -g npm 12 | # install dependencies 13 | - npm install --silent --progress=false -g serverless 14 | - npm install --silent --progress-false 15 | - npm --version 16 | build: 17 | commands: 18 | # linting and unit tests 19 | - npm run-script lint 20 | - npm test 21 | # deploy integration testing environment 22 | - serverless deploy --stage test -v 23 | # integration tests 24 | - npm run-script integration 25 | # create directory for deployment packages 26 | - mkdir artifacts 27 | # create staging deployment package 28 | - mkdir artifacts/stg 29 | - serverless package --package artifacts/stg --stage stg -v 30 | # create prod deployment package 31 | - mkdir artifacts/prod 32 | - serverless package --package artifacts/prod --stage prod -v 33 | post_build: 34 | commands: 35 | # tear down integration testing environment 36 | - serverless remove --stage test -v 37 | 38 | artifacts: 39 | files: 40 | # export artifacts needed for staging and prod deployments to an S3 bucket 41 | - artifacts/**/* 42 | - serverless.yml 43 | - deploy.sh 44 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | echo "Installing serverless" 4 | echo "=====================" 5 | npm install -g serverless 6 | npm install serverless-dynamodb-local serverless-offline serverless-stack-output # we have to install the three plugins specified in our serverless.yml to avoid errors, even though we won't be using them 7 | 8 | echo "Deploying app to $env" 9 | echo "=====================" 10 | serverless deploy --stage $env --package $CODEBUILD_SRC_DIR/artifacts/$env -v 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "serverless-ci-cd", 3 | "version": "1.0.0", 4 | "description": "Demo Serverless project using CodeBuild and CodePipeline for CI/CD. Tutorial available at http://www.1strategy.com/blog/.", 5 | "main": "handler.js", 6 | "scripts": { 7 | "test": "jest __tests__/unit/*", 8 | "lint": "eslint */*.js", 9 | "integration": "jest __tests__/integration/*" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/1Strategy/serverless-ci-cd.git" 14 | }, 15 | "author": "1Strategy", 16 | "license": "Apache-2.0", 17 | "bugs": { 18 | "url": "https://github.com/1Strategy/serverless-ci-cd/issues" 19 | }, 20 | "homepage": "https://github.com/1Strategy/serverless-ci-cd#readme", 21 | "devDependencies": { 22 | "eslint": "^4.9.0", 23 | "eslint-config-airbnb": "^16.1.0", 24 | "eslint-config-airbnb-base": "^12.1.0", 25 | "eslint-plugin-import": "^2.7.0", 26 | "eslint-plugin-jest": "^21.5.0", 27 | "eslint-plugin-jsx-a11y": "^6.0.3", 28 | "eslint-plugin-react": "^7.5.1", 29 | "jest": "^22.0.3", 30 | "serverless-dynamodb-local": "^0.2.26", 31 | "serverless-offline": "^3.16.0", 32 | "serverless-stack-output": "^0.2.3", 33 | "supertest": "^3.0.0" 34 | }, 35 | "dependencies": { 36 | "serverless-dynamodb-client": "0.0.2", 37 | "uuid": "^3.1.0" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: serverless-ci-cd 2 | 3 | provider: 4 | name: aws 5 | runtime: nodejs6.10 # AWS Lambda supports v.4.3.2 and v.6.10.3 6 | 7 | # Overwrite defaults 8 | memorySize: 512 # overwrite default memory of 1024 9 | versionFunctions: false # don't create a new function version with each deploy 10 | region: us-west-2 # override default region us-east-1 11 | 12 | # Service-wide environment variables 13 | environment: 14 | STAGE: ${opt:stage} 15 | 16 | # Add statements to the Lambda function's IAM Role 17 | iamRoleStatements: 18 | - Effect: "Allow" 19 | Action: 20 | - dynamodb:DescribeTable 21 | - dynamodb:Scan 22 | - dynamodb:Query 23 | - dynamodb:GetItem 24 | - dynamodb:PutItem 25 | - dynamodb:UpdateItem 26 | - dynamodb:DeleteItem 27 | Resource: "arn:aws:dynamodb:us-west-2:*:*" 28 | 29 | # Define our lambda functions and the events they respond to 30 | functions: 31 | listTodos: 32 | handler: todos/handler.list 33 | events: 34 | - http: 35 | path: todos 36 | method: get 37 | postTodos: 38 | handler: todos/handler.post 39 | events: 40 | - http: 41 | path: todos 42 | method: post 43 | 44 | # Define CloudFormation resource templates here 45 | resources: 46 | Resources: 47 | TodosDB: 48 | Type: 'AWS::DynamoDB::Table' 49 | Properties: 50 | TableName: 'Todos-${opt:stage}' 51 | # here we define the primary key of the table. 52 | AttributeDefinitions: 53 | - 54 | AttributeName: 'id' 55 | AttributeType: S 56 | KeySchema: 57 | - 58 | AttributeName: 'id' 59 | KeyType: HASH 60 | ProvisionedThroughput: 61 | ReadCapacityUnits: '1' 62 | WriteCapacityUnits: '1' 63 | 64 | custom: 65 | dynamodb: 66 | start: 67 | port: 8000 68 | # uncomment for already-running local DynamoDB 69 | # noStart: true 70 | output: 71 | file: .build/stack.json # where stack output should be stored by the serverless-stack-output plugin 72 | 73 | plugins: 74 | - serverless-dynamodb-local # use this with serverless-offline to create local dev environment 75 | - serverless-offline 76 | - serverless-stack-output # store stack output in a file 77 | -------------------------------------------------------------------------------- /todos/handler.js: -------------------------------------------------------------------------------- 1 | const dynamoDbClient = require('serverless-dynamodb-client'); 2 | const Todos = require('./todos.js'); 3 | 4 | const dynamoDb = dynamoDbClient.doc; 5 | const todos = new Todos(dynamoDb, `Todos-${process.env.STAGE}`); 6 | 7 | module.exports.list = (event, context, callback) => { 8 | todos.list(callback); 9 | }; 10 | 11 | module.exports.post = (event, context, callback) => { 12 | const body = JSON.parse(event.body); 13 | todos.post(body, callback); 14 | }; 15 | -------------------------------------------------------------------------------- /todos/todos.js: -------------------------------------------------------------------------------- 1 | const uuidv4 = require('uuid/v4'); 2 | 3 | class Todos { 4 | constructor(db, tableName) { 5 | this.db = db; 6 | this.tableName = tableName; 7 | } 8 | 9 | list(callback) { 10 | const params = { 11 | TableName: this.tableName 12 | }; 13 | 14 | this.db.scan( 15 | params, 16 | (err, todos) => { 17 | if (err) { 18 | console.error(err); 19 | callback(`Failed to get all todos, with error: ${err}`); 20 | return; 21 | } 22 | 23 | const response = { 24 | statusCode: 200, 25 | body: JSON.stringify(todos.Items) 26 | }; 27 | 28 | callback(null, response); 29 | } 30 | ); 31 | } 32 | 33 | post(body, callback) { 34 | const params = { 35 | TableName: this.tableName, 36 | Item: { 37 | id: uuidv4(), 38 | title: body.title, 39 | completed: body.completed, 40 | updatedAt: Date.now() 41 | }, 42 | ConditionExpression: 'attribute_not_exists(id)', 43 | ReturnConsumedCapacity: 'NONE' 44 | }; 45 | 46 | this.db.put( 47 | params, 48 | (err, todo) => { 49 | if (err) { 50 | console.error(err); 51 | callback(`Failed to create todo, with error: ${err}`); 52 | return; 53 | } 54 | 55 | const response = { 56 | statusCode: 200, 57 | body: JSON.stringify(todo) 58 | // TODO: dynamoDB only returns empty object for a PUT; 59 | // return actual object in response 60 | }; 61 | 62 | callback(null, response); 63 | } 64 | ); 65 | } 66 | } 67 | 68 | module.exports = Todos; 69 | --------------------------------------------------------------------------------