├── .editorconfig ├── .github └── workflows │ ├── integrate.yml │ ├── publish.yml │ └── validate.yml ├── .gitignore ├── .npmrc ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYRIGHT ├── LICENSE ├── README.md ├── assets └── deploy-demo.gif ├── package.json ├── prettier.config.js ├── scripts └── install-nested-packages.js ├── serverless.component.yml ├── src ├── package-lock.json ├── package.json ├── serverless.js └── utils.js ├── templates └── aws-dynamodb-starter │ ├── .gitignore │ ├── serverless.template.yml │ └── serverless.yml └── test ├── integration.test.js └── utils.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | end_of_line = lf 9 | insert_final_newline = true 10 | indent_size = 2 11 | indent_style = space 12 | trim_trailing_whitespace = true 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /.github/workflows/integrate.yml: -------------------------------------------------------------------------------- 1 | # master only 2 | 3 | name: Integrate 4 | 5 | on: 6 | push: 7 | branches: [master] 8 | 9 | env: 10 | FORCE_COLOR: 1 11 | 12 | jobs: 13 | validate: 14 | name: Validate 15 | runs-on: ubuntu-latest 16 | env: 17 | SERVERLESS_ACCESS_KEY: ${{ secrets.SERVERLESS_ACCESS_KEY }} 18 | steps: 19 | - name: Resolve last validated commit hash (for `git diff` purposes) 20 | env: 21 | # See https://github.com/serverlessinc/setup-cicd-resources 22 | GET_LAST_VALIDATED_COMMIT_HASH_URL: ${{ secrets.GET_LAST_VALIDATED_COMMIT_HASH_URL }} 23 | PUT_LAST_VALIDATED_COMMIT_HASH_URL: ${{ secrets.PUT_LAST_VALIDATED_COMMIT_HASH_URL }} 24 | run: | 25 | curl -f "$GET_LAST_VALIDATED_COMMIT_HASH_URL" -o /home/runner/last-validated-commit-hash || : 26 | curl -v -X PUT -H "User-Agent:" -H "Accept:" -H "Content-Type:" -d "$GITHUB_SHA" "$PUT_LAST_VALIDATED_COMMIT_HASH_URL" 27 | - name: Store last validated commit hash (as it's to be used in other job) 28 | uses: actions/upload-artifact@v2 29 | with: 30 | name: last-validated-commit-hash 31 | path: /home/runner/last-validated-commit-hash 32 | 33 | - name: Checkout repository 34 | uses: actions/checkout@v2 35 | 36 | - name: Retrieve ~/.npm from cache 37 | uses: actions/cache@v1 38 | with: 39 | path: ~/.npm 40 | key: npm-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('**package*.json') }} 41 | restore-keys: npm-v14-${{ runner.os }}-${{ github.ref }}- 42 | - name: Retrieve node_modules from cache 43 | id: cacheNodeModules 44 | uses: actions/cache@v1 45 | with: 46 | path: node_modules 47 | key: node-modules-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('package.json') }} 48 | restore-keys: node-modules-v14-${{ runner.os }}-${{ github.ref }}- 49 | - name: Retrieve src/node_modules from cache 50 | id: cacheSrcNodeModules 51 | uses: actions/cache@v1 52 | with: 53 | path: src/node_modules 54 | key: src/node-modules-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('src/package*.json') }} 55 | restore-keys: src/node-modules-v14-${{ runner.os }}-${{ github.ref }}- 56 | 57 | - name: Install Node.js and npm 58 | uses: actions/setup-node@v1 59 | with: 60 | node-version: 14.x 61 | 62 | - name: Install root dependencies 63 | if: steps.cacheNodeModules.outputs.cache-hit != 'true' 64 | run: npm update --save-dev --no-save 65 | - name: Install src dependencies 66 | if: steps.cacheSrcNodeModules.outputs.cache-hit != 'true' 67 | run: | 68 | cd src 69 | npm ci 70 | 71 | # Ensure no parallel runs 72 | # See: https://github.community/t/how-to-limit-concurrent-workflow-runs/16844/21 73 | - name: Turnstyle 74 | uses: softprops/turnstyle@v1 75 | env: 76 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 77 | 78 | - name: Publish "dev" version 79 | run: npm run publish:dev 80 | 81 | - name: Integration tests 82 | env: 83 | AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} 84 | AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 85 | run: npm test 86 | 87 | tagIfNewVersion: 88 | name: Tag if new version 89 | runs-on: ubuntu-latest 90 | needs: validate 91 | steps: 92 | - name: Checkout repository 93 | uses: actions/checkout@v2 94 | with: 95 | # Ensure to have complete history of commits pushed with given push operation 96 | # It's loose and imperfect assumption that no more than 30 commits will be pushed at once 97 | fetch-depth: 30 98 | # Tag needs to be pushed with real user token 99 | # (hence we're not relying on actions secrets.GITHUB_TOKEN) 100 | # Otherwise pushed tag won't trigger the actions workflow 101 | token: ${{ secrets.USER_GITHUB_TOKEN }} 102 | 103 | - name: Resolve last validated commit hash (for `git diff` purposes) 104 | uses: actions/download-artifact@v2 105 | continue-on-error: true 106 | with: 107 | name: last-validated-commit-hash 108 | path: /home/runner 109 | 110 | - name: Tag if new version 111 | run: | 112 | LAST_VALIDATED_COMMIT_HASH=`cat /home/runner/last-validated-commit-hash` || : 113 | if [ -n "$LAST_VALIDATED_COMMIT_HASH" ]; 114 | then 115 | NEW_VERSION=`git diff -U0 $LAST_VALIDATED_COMMIT_HASH serverless.component.yml | grep 'version: ' | tail -n 1 | grep -oE "[0-9]+\.[0-9]+\.[0-9]+"` || : 116 | if [ -n "$NEW_VERSION" ]; 117 | then 118 | git tag v$NEW_VERSION 119 | git push --tags 120 | fi 121 | fi 122 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | # Version tags only 2 | 3 | name: Publish 4 | 5 | on: 6 | push: 7 | tags: 8 | - v[0-9]+.[0-9]+.[0-9]+ 9 | 10 | env: 11 | FORCE_COLOR: 1 12 | 13 | jobs: 14 | publish: 15 | name: Publish 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v2 20 | 21 | - name: Retrieve node_modules from cache 22 | uses: actions/cache@v1 23 | with: 24 | path: node_modules 25 | key: node-modules-v14-${{ runner.os }}-refs/heads/master-${{ hashFiles('package.json') }} 26 | - name: Retrieve src/node_modules from cache 27 | uses: actions/cache@v1 28 | with: 29 | path: src/node_modules 30 | key: src/node-modules-v14-${{ runner.os }}-refs/heads/master-${{ hashFiles('src/package*.json') }} 31 | 32 | - name: Install Node.js and npm 33 | uses: actions/setup-node@v1 34 | with: 35 | node-version: 14.x 36 | 37 | - name: Publish new version 38 | env: 39 | SERVERLESS_ACCESS_KEY: ${{ secrets.SERVERLESS_ACCESS_KEY }} 40 | run: npm run publish 41 | -------------------------------------------------------------------------------- /.github/workflows/validate.yml: -------------------------------------------------------------------------------- 1 | # PR's only 2 | 3 | name: Validate 4 | 5 | on: 6 | pull_request: 7 | branches: [master] 8 | 9 | env: 10 | FORCE_COLOR: 1 11 | 12 | jobs: 13 | lintAndFormatting: 14 | name: Lint & Formatting 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v2 19 | 20 | - name: Retrieve last master commit (for `git diff` purposes) 21 | run: | 22 | git checkout -b pr 23 | git fetch --prune --depth=1 origin +refs/heads/master:refs/remotes/origin/master 24 | git checkout master 25 | git checkout pr 26 | 27 | - name: Retrieve ~/.npm from cache 28 | uses: actions/cache@v1 29 | with: 30 | path: ~/.npm 31 | key: npm-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('**package*.json') }} 32 | restore-keys: | 33 | npm-v14-${{ runner.os }}-${{ github.ref }}- 34 | npm-v14-${{ runner.os }}-refs/heads/master- 35 | - name: Retrieve node_modules from cache 36 | id: cacheNodeModules 37 | uses: actions/cache@v1 38 | with: 39 | path: node_modules 40 | key: node-modules-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('package.json') }} 41 | restore-keys: | 42 | node-modules-v14-${{ runner.os }}-${{ github.ref }}- 43 | node-modules-v14-${{ runner.os }}-refs/heads/master- 44 | - name: Retrieve src/node_modules from cache 45 | id: cacheSrcNodeModules 46 | uses: actions/cache@v1 47 | with: 48 | path: src/node_modules 49 | key: src/node-modules-v14-${{ runner.os }}-${{ github.ref }}-${{ hashFiles('src/package*.json') }} 50 | restore-keys: | 51 | src/node-modules-v14-${{ runner.os }}-${{ github.ref }}- 52 | src/node-modules-v14-${{ runner.os }}-refs/heads/master- 53 | 54 | - name: Install Node.js and npm 55 | uses: actions/setup-node@v1 56 | with: 57 | node-version: 14.x 58 | 59 | - name: Install root dependencies 60 | if: steps.cacheNodeModules.outputs.cache-hit != 'true' 61 | run: npm update --save-dev --no-save 62 | - name: Install src dependencies 63 | if: steps.cacheSrcNodeModules.outputs.cache-hit != 'true' 64 | run: | 65 | cd src 66 | npm ci 67 | 68 | - name: Validate Formatting 69 | run: npm run prettier-check:updated 70 | - name: Validate Lint rules 71 | run: npm run lint:updated 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env* 2 | /.eslintcache 3 | /node_modules 4 | /package-lock.json 5 | /src/node_modules 6 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting our team at **hello@serverless.com**. As an alternative 59 | feel free to reach out to any of us personally. All 60 | complaints will be reviewed and investigated and will result in a response that 61 | is deemed necessary and appropriate to the circumstances. The project team is 62 | obligated to maintain confidentiality with regard to the reporter of an incident. 63 | Further details of specific enforcement policies may be posted separately. 64 | 65 | Project maintainers who do not follow or enforce the Code of Conduct in good 66 | faith may face temporary or permanent repercussions as determined by other 67 | members of the project's leadership. 68 | 69 | ## Attribution 70 | 71 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 72 | available at [http://contributor-covenant.org/version/1/4][version] 73 | 74 | [homepage]: http://contributor-covenant.org 75 | [version]: http://contributor-covenant.org/version/1/4/ 76 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a [code of conduct](./CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. 7 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Serverless, Inc. https://serverless.com 2 | 3 | Serverless Components may be freely distributed under the Apache 2.0 license. 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://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 | Copyright 2018 Serverless, Inc. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | https://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Serverless Components](https://s3.amazonaws.com/public.assets.serverless.com/images/readme_serverless_components.gif)](http://serverless.com) 2 | 3 |
4 | 5 |

6 | Click Here for Version 1.0 7 |

8 | 9 |
10 | 11 | **AWS DynamoDB Component** ⎯⎯⎯ The easiest way to deploy & manage AWS DynamoDB tables, powered by [Serverless Components](https://github.com/serverless/components/tree/cloud). 12 | 13 |
14 | 15 | - [x] **Minimal Configuration** - With built-in sane defaults. 16 | - [x] **Fast Deployments** - Create & update tables in seconds. 17 | - [x] **Team Collaboration** - Share your table outputs with your team's components. 18 | - [x] **Easy Management** - Easily manage and monitor your tables with the Serverless Dashboard. 19 | 20 |
21 | 22 | Check out the **[Serverless Fullstack Application](https://github.com/serverless-components/fullstack-app)** for a ready-to-use boilerplate and overall great example of how to use this Component. 23 | 24 |
25 | 26 | 27 | 28 | 1. [**Install**](#1-install) 29 | 2. [**Initialize**](#2-initialize) 30 | 3. [**Deploy**](#3-deploy) 31 | 4. [**Configure**](#4-configure) 32 | 5. [**Develop**](#5-develop) 33 | 6. [**Monitor**](#6-monitor) 34 | 7. [**Remove**](#7-remove) 35 | 36 |   37 | 38 | ### 1. Install 39 | 40 | To get started with component, install the latest version of the Serverless Framework: 41 | 42 | ``` 43 | $ npm install -g serverless 44 | ``` 45 | 46 | After installation, make sure you connect your AWS account by setting a provider in the org setting page on the [Serverless Dashboard](https://app.serverless.com). 47 | 48 | ### 2. Initialize 49 | 50 | The easiest way to start using the `aws-dynamodb` component is by initializing the `aws-dynamodb-starter` template. Just run this command: 51 | 52 | ``` 53 | $ serverless init aws-dynamodb-starter 54 | $ cd aws-dynamodb-starter 55 | ``` 56 | 57 | ### 3. Deploy 58 | 59 | Once you have the directory set up, you're now ready to deploy. Just run the following command from within the directory containing the `serverless.yml` file: 60 | 61 | ``` 62 | $ serverless deploy 63 | ``` 64 | 65 | Your first deployment might take a little while, but subsequent deployment would just take few seconds. For more information on what's going on during deployment, you could specify the `--debug` flag, which would view deployment logs in realtime: 66 | 67 | ``` 68 | $ serverless deploy --debug 69 | ``` 70 | 71 | ### 4. Configure 72 | 73 | The `aws-dynamodb` component requires minimal configuration with built-in sane defaults. Here's a complete reference of the `serverless.yml` file for the `aws-dynamodb` component: 74 | 75 | ```yml 76 | component: aws-dynamodb # (required) name of the component. In that case, it's aws-dynamodb. 77 | name: my-table # (required) name of your instance. 78 | org: serverlessinc # (optional) serverless dashboard org. default is the first org you created during signup. 79 | app: myApp # (optional) serverless dashboard app. default is the same as the name property. 80 | stage: dev # (optional) serverless dashboard stage. default is dev. 81 | 82 | inputs: 83 | name: my-table 84 | attributeDefinitions: 85 | - AttributeName: id 86 | AttributeType: S 87 | - AttributeName: attribute1 88 | AttributeType: N 89 | keySchema: 90 | - AttributeName: id 91 | KeyType: HASH 92 | - AttributeName: attribute1 93 | KeyType: RANGE 94 | localSecondaryIndexes: 95 | - IndexName: 'myLocalSecondaryIndex' 96 | KeySchema: 97 | - AttributeName: id 98 | KeyType: HASH 99 | - AttributeName: attribute2 100 | KeyType: RANGE 101 | Projection: 102 | ProjectionType: 'KEYS_ONLY' 103 | globalSecondaryIndexes: 104 | - IndexName: 'myGlobalSecondaryIndex' 105 | KeySchema: 106 | - AttributeName: attribute2 107 | KeyType: HASH 108 | Projection: 109 | ProjectionType: 'ALL' 110 | region: us-east-1 111 | ``` 112 | 113 | Once you've chosen your configuration, run `serverless deploy` again (or simply just `serverless`) to deploy your changes. Please keep in mind that `localSecondaryIndexes` cannot be updated after first deployment. This is an AWS limitation. Also note that this component exclusively uses the [Pay Per Request](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BillingModeSummary.html) pricing, which scales on demand like any serverless offering. 114 | 115 | ### 5. Develop 116 | 117 | Instead of having to run `serverless deploy` everytime you make changes you wanna test, you could enable dev mode, which allows the CLI to watch for changes in your configuration file, and deploy instantly on save. 118 | 119 | To enable dev mode, just run the following command: 120 | 121 | ``` 122 | $ serverless dev 123 | ``` 124 | 125 | ### 6. Monitor 126 | 127 | Anytime you need to know more about your running `aws-dynamodb` instance, you can run the following command to view the most critical info. 128 | 129 | ``` 130 | $ serverless info 131 | ``` 132 | 133 | This is especially helpful when you want to know the outputs of your instances so that you can reference them in another instance. It also shows you the status of your instance, when it was last deployed, and how many times it was deployed. You will also see a url where you'll be able to view more info about your instance on the Serverless Dashboard. 134 | 135 | To digg even deeper, you can pass the `--debug` flag to view the state of your component instance in case the deployment failed for any reason. 136 | 137 | ``` 138 | $ serverless info --debug 139 | ``` 140 | 141 | ### 7. Remove 142 | 143 | If you wanna tear down your entire `aws-dynamodb` infrastructure that was created during deployment, just run the following command in the directory containing the `serverless.yml` file. 144 | 145 | ``` 146 | $ serverless remove 147 | ``` 148 | 149 | The `aws-dynamodb` component will then use all the data it needs from the built-in state storage system to delete only the relavent cloud resources that it created. Just like deployment, you could also specify a `--debug` flag for realtime logs from the website component running in the cloud. 150 | 151 | ``` 152 | $ serverless remove --debug 153 | ``` 154 | -------------------------------------------------------------------------------- /assets/deploy-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serverless-components/aws-dynamodb/476817c3bd37c1af1fbcb282dd93c9c79580e644/assets/deploy-demo.gif -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@serverless-components/aws-dynamodb", 3 | "private": true, 4 | "author": "Serverless, Inc.", 5 | "license": "Apache", 6 | "scripts": { 7 | "lint": "eslint --ignore-path .gitignore .", 8 | "lint:updated": "pipe-git-updated --ext=js -- eslint --ignore-path .gitignore .", 9 | "postinstall": "./scripts/install-nested-packages.js", 10 | "prettier-check": "prettier -c --ignore-path .gitignore \"**/*.{css,html,js,json,yaml,yml}\"", 11 | "prettier-check:updated": "pipe-git-updated --ext=css --ext=html --ext=js --ext=json --ext=yaml --ext=yml -- prettier -c", 12 | "prettify": "prettier --write --ignore-path .gitignore \"**/*.{css,html,js,json,yaml,yml}\"", 13 | "prettify:updated": "pipe-git-updated --ext=css --ext=html --ext=js --ext=json --ext=yaml --ext=yml -- prettier --write", 14 | "publish": "components registry publish", 15 | "publish:dev": "components registry publish --dev", 16 | "test": "jest --bail 1 --testEnvironment node ./test/integration.test.js" 17 | }, 18 | "devDependencies": { 19 | "@serverless/components": "^2.31.7", 20 | "@serverless/eslint-config": "^2.1.1", 21 | "@serverless/platform-client": "^0.24.0", 22 | "aws-sdk": "^2.707.0", 23 | "dotenv": "^8.2.0", 24 | "eslint": "^7.3.1", 25 | "eslint-plugin-import": "^2.22.0", 26 | "eslint-plugin-prettier": "^3.1.4", 27 | "git-list-updated": "^1.2.1", 28 | "jest": "^25.5.4", 29 | "prettier": "^2.0.5" 30 | }, 31 | "eslintConfig": { 32 | "extends": "@serverless/eslint-config/node", 33 | "root": true, 34 | "rules": { 35 | "no-console": "off" 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = require('@serverless/eslint-config/prettier.config'); 4 | -------------------------------------------------------------------------------- /scripts/install-nested-packages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | process.on('unhandledRejection', (reason) => { 6 | throw reason; 7 | }); 8 | 9 | const path = require('path'); 10 | const childProcess = require('child_process'); 11 | 12 | const platformRoot = path.resolve(__dirname, '..'); 13 | 14 | const npmInstall = (packagePath) => 15 | new Promise((resolve, reject) => { 16 | console.log('---------------------------------------'); 17 | console.log(`Install \x1b[33m${packagePath}\x1b[39m ...\n`); 18 | const child = childProcess.spawn('npm', ['install'], { 19 | cwd: path.resolve(platformRoot, packagePath), 20 | stdio: 'inherit', 21 | }); 22 | child.on('error', reject); 23 | child.on('close', (code) => { 24 | if (code) { 25 | reject(new Error(`npm install failed at ${packagePath}`)); 26 | } else { 27 | resolve(); 28 | } 29 | }); 30 | }); 31 | 32 | const packagesPaths = ['src']; 33 | 34 | (async () => { 35 | // Running multiple "npm install" prcesses in parallel is not confirmed to be safe. 36 | for (const packagePath of packagesPaths) { 37 | await npmInstall(packagePath); 38 | } 39 | })(); 40 | -------------------------------------------------------------------------------- /serverless.component.yml: -------------------------------------------------------------------------------- 1 | name: aws-dynamodb 2 | version: 1.1.3 3 | author: ac360 4 | org: serverlessinc 5 | description: Provision an AWS DynamoDB Table 6 | keywords: aws, serverless, dynamodb, database 7 | repo: https://github.com/serverless-components/aws-dynamodb 8 | readme: '' 9 | license: MIT 10 | main: ./src 11 | types: 12 | providers: 13 | - aws -------------------------------------------------------------------------------- /src/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "src", 3 | "lockfileVersion": 2, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "license": "Apache", 8 | "dependencies": { 9 | "ramda": "^0.26.0" 10 | } 11 | }, 12 | "node_modules/ramda": { 13 | "version": "0.26.1", 14 | "resolved": "https://registry.npmjs.org/ramda/-/ramda-0.26.1.tgz", 15 | "integrity": "sha512-hLWjpy7EnsDBb0p+Z3B7rPi3GDeRG5ZtiI33kJhTt+ORCd38AbAIjB/9zRIUoeTbE/AVX5ZkU7m6bznsvrf8eQ==" 16 | } 17 | }, 18 | "dependencies": { 19 | "ramda": { 20 | "version": "0.26.1", 21 | "resolved": "https://registry.npmjs.org/ramda/-/ramda-0.26.1.tgz", 22 | "integrity": "sha512-hLWjpy7EnsDBb0p+Z3B7rPi3GDeRG5ZtiI33kJhTt+ORCd38AbAIjB/9zRIUoeTbE/AVX5ZkU7m6bznsvrf8eQ==" 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "./serverless.js", 3 | "author": "Serverless, Inc.", 4 | "license": "Apache", 5 | "dependencies": { 6 | "ramda": "^0.26.0" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/serverless.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { mergeDeepRight, pick } = require('ramda'); 4 | // eslint-disable-next-line import/no-extraneous-dependencies 5 | const AWS = require('aws-sdk'); 6 | // eslint-disable-next-line import/no-unresolved 7 | const { Component } = require('@serverless/core'); 8 | const { log, createTable, deleteTable, describeTable, updateTable } = require('./utils'); 9 | 10 | const outputsList = ['name', 'arn', 'region']; 11 | 12 | const defaults = { 13 | attributeDefinitions: [ 14 | { 15 | AttributeName: 'id', 16 | AttributeType: 'S', 17 | }, 18 | ], 19 | keySchema: [ 20 | { 21 | AttributeName: 'id', 22 | KeyType: 'HASH', 23 | }, 24 | ], 25 | globalSecondaryIndexes: [], 26 | localSecondaryIndexes: [], 27 | name: null, 28 | region: 'us-east-1', 29 | deletionPolicy: 'delete', 30 | }; 31 | 32 | class AwsDynamoDb extends Component { 33 | async deploy(inputs = {}) { 34 | const config = mergeDeepRight(defaults, inputs); 35 | config.name = config.name || this.name; 36 | 37 | // If first deploy and no name is found, set default name.. 38 | if (!config.name && !this.state.name) { 39 | config.name = `dynamodb-table-${Math.random().toString(36).substring(6)}`; 40 | this.state.name = config.name; 41 | } 42 | // If first deploy, and a name is set... 43 | else if (config.name && !this.state.name) { 44 | this.state.name = config.name; 45 | } 46 | // If subequent deploy, and name is different from a previously used name, throw error. 47 | else if (config.name && this.state.name && config.name !== this.state.name) { 48 | throw new Error( 49 | 'You cannot change the name of your DynamoDB table once it has been deployed (or this will deploy a new table). Please remove this Component Instance first by running "serverless remove", then redeploy it with "serverless deploy".' 50 | ); 51 | } 52 | 53 | console.log(`Starting deployment of table ${config.name} in the ${config.region} region.`); 54 | 55 | const dynamodb = new AWS.DynamoDB({ 56 | region: config.region, 57 | credentials: this.credentials.aws, 58 | }); 59 | 60 | console.log(`Checking if table ${config.name} already exists in the ${config.region} region.`); 61 | 62 | const prevTable = await describeTable({ dynamodb, name: config.name }); 63 | 64 | if (!prevTable) { 65 | log(`Table ${config.name} does not exist. Creating...`); 66 | 67 | config.arn = await createTable({ dynamodb, ...config }); 68 | } else { 69 | console.log(`Table ${config.name} already exists. Comparing config changes...`); 70 | 71 | // Check region 72 | if (config.region && this.state.region && config.region !== this.state.region) { 73 | throw new Error( 74 | 'You cannot change the region of a DynamoDB Table. Please remove it and redeploy in your desired region.' 75 | ); 76 | } 77 | 78 | config.arn = prevTable.arn; 79 | 80 | const prevGlobalSecondaryIndexes = prevTable.globalSecondaryIndexes || []; 81 | await updateTable.call(this, { dynamodb, prevGlobalSecondaryIndexes, ...config }); 82 | } 83 | 84 | log(`Table ${config.name} was successfully deployed to the ${config.region} region.`); 85 | 86 | this.state.arn = config.arn; 87 | this.state.name = config.name; 88 | this.state.region = config.region; 89 | this.state.deletionPolicy = config.deletionPolicy; 90 | 91 | const outputs = pick(outputsList, config); 92 | 93 | // Add indexes to outputs as objects, which are easier to reference as serverless variables 94 | if (config.globalSecondaryIndexes) { 95 | outputs.indexes = outputs.indexes || {}; 96 | config.globalSecondaryIndexes.forEach((index) => { 97 | outputs.indexes[index.IndexName] = { 98 | name: index.IndexName, 99 | arn: `${outputs.arn}/index/${index.IndexName}`, 100 | }; 101 | }); 102 | } 103 | 104 | if (config.localSecondaryIndexes) { 105 | outputs.indexes = outputs.indexes || {}; 106 | config.localSecondaryIndexes.forEach((index) => { 107 | outputs.indexes[index.IndexName] = { 108 | name: index.IndexName, 109 | arn: `${outputs.arn}/index/${index.IndexName}`, 110 | }; 111 | }); 112 | } 113 | 114 | return outputs; 115 | } 116 | 117 | /** 118 | * Remove 119 | */ 120 | async remove() { 121 | console.log('Removing'); 122 | 123 | // If "delete: false", don't delete the table, and warn instead 124 | if (this.state.deletionPolicy && this.state.deletionPolicy === 'retain') { 125 | console.log('Skipping table removal because "deletionPolicy" is set to "retain".'); 126 | this.state = {}; 127 | return {}; 128 | } 129 | 130 | const { name, region } = this.state; 131 | 132 | if (!name) { 133 | console.log('Aborting removal. Table name not found in state.'); 134 | return null; 135 | } 136 | 137 | const dynamodb = new AWS.DynamoDB({ 138 | region, 139 | credentials: this.credentials.aws, 140 | }); 141 | 142 | console.log(`Removing table ${name} from the ${region} region.`); 143 | 144 | await deleteTable({ dynamodb, name }); 145 | 146 | const outputs = pick(outputsList, this.state); 147 | 148 | console.log(`Table ${name} was successfully removed from the ${region} region.`); 149 | 150 | this.state = {}; 151 | return outputs; 152 | } 153 | } 154 | 155 | module.exports = AwsDynamoDb; 156 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { isEmpty } = require('ramda'); 4 | 5 | function log(msg) { 6 | return console.log(msg); 7 | } 8 | 9 | async function createTable({ 10 | dynamodb, 11 | name, 12 | attributeDefinitions, 13 | keySchema, 14 | globalSecondaryIndexes, 15 | localSecondaryIndexes, 16 | }) { 17 | const res = await dynamodb 18 | .createTable({ 19 | TableName: name, 20 | AttributeDefinitions: attributeDefinitions, 21 | KeySchema: keySchema, 22 | GlobalSecondaryIndexes: globalSecondaryIndexes.length ? globalSecondaryIndexes : undefined, 23 | LocalSecondaryIndexes: localSecondaryIndexes.length ? localSecondaryIndexes : undefined, 24 | BillingMode: 'PAY_PER_REQUEST', 25 | }) 26 | .promise(); 27 | return res.TableDescription.TableArn; 28 | } 29 | 30 | async function describeTable({ dynamodb, name }) { 31 | try { 32 | const data = await dynamodb.describeTable({ TableName: name }).promise(); 33 | return { 34 | arn: data.Table.TableArn, 35 | name: data.Table.TableName, 36 | attributeDefinitions: data.Table.AttributeDefinitions, 37 | keySchema: data.Table.KeySchema, 38 | globalSecondaryIndexes: data.Table.GlobalSecondaryIndexes, 39 | }; 40 | } catch (error) { 41 | if (error.code === 'ResourceNotFoundException') { 42 | return null; 43 | } 44 | } 45 | return null; 46 | } 47 | 48 | async function updateTable({ 49 | dynamodb, 50 | prevGlobalSecondaryIndexes, 51 | globalSecondaryIndexes, 52 | name, 53 | attributeDefinitions, 54 | }) { 55 | // find a globalSecondaryIndex that is not in any previous globalSecondaryIndex 56 | const toCreate = globalSecondaryIndexes.filter( 57 | (globalSecondardyIndex) => 58 | prevGlobalSecondaryIndexes.findIndex( 59 | (element) => element.IndexName === globalSecondardyIndex.IndexName 60 | ) === -1 61 | ); 62 | 63 | // If previous globalSecondaryIndex has an item that is not now present, then delete 64 | const toDelete = prevGlobalSecondaryIndexes 65 | .filter( 66 | (prevGlobalSecondaryIndex) => 67 | globalSecondaryIndexes.findIndex( 68 | (element) => element.IndexName === prevGlobalSecondaryIndex.IndexName 69 | ) === -1 70 | ) 71 | .map(({ IndexName }) => ({ IndexName })); 72 | 73 | // Only take the first item since only one delete and create can be done at a time 74 | const indexUpdates = {}; 75 | if (toCreate.length) { 76 | indexUpdates.Create = toCreate[0]; 77 | if (toCreate.length > 1) { 78 | console.log( 79 | `Only ${toCreate[0].IndexName} will be created since a limitation of Dynamodb is that only one Gloabl secondary index can be created during an upate. 80 | Run this operation after the index has been created on AWS to create the additional indexes` 81 | ); 82 | } 83 | } 84 | if (toDelete.length) { 85 | indexUpdates.Delete = toDelete[0]; 86 | if (toDelete.length > 1) { 87 | console.log( 88 | `Only ${toDelete[0].IndexName} will be deleted since a limitation of Dynamodb is that only one Gloabl secondary index can be deleted during an upate. 89 | Run this operation after the index has been deleted on AWS to delete the additional indexes` 90 | ); 91 | } 92 | } 93 | const res = await dynamodb 94 | .updateTable({ 95 | TableName: name, 96 | AttributeDefinitions: attributeDefinitions, 97 | BillingMode: 'PAY_PER_REQUEST', 98 | GlobalSecondaryIndexUpdates: !isEmpty(indexUpdates) ? [indexUpdates] : undefined, 99 | }) 100 | .promise(); 101 | 102 | return res.TableDescription.TableArn; 103 | } 104 | 105 | async function deleteTable({ dynamodb, name }) { 106 | let res = false; 107 | try { 108 | res = await dynamodb 109 | .deleteTable({ 110 | TableName: name, 111 | }) 112 | .promise(); 113 | } catch (error) { 114 | console.log('AWS remove error', error); 115 | if (error.code !== 'ResourceNotFoundException') { 116 | throw error; 117 | } 118 | } 119 | return !!res; 120 | } 121 | 122 | module.exports = { 123 | log, 124 | createTable, 125 | describeTable, 126 | updateTable, 127 | deleteTable, 128 | }; 129 | -------------------------------------------------------------------------------- /templates/aws-dynamodb-starter/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.sublime-project 3 | *.sublime-workspace 4 | *.log 5 | .serverless 6 | v8-compile-cache-* 7 | jest/* 8 | coverage 9 | testProjects/*/package-lock.json 10 | testProjects/*/yarn.lock 11 | .serverlessUnzipped 12 | node_modules 13 | .vscode/ 14 | .eslintcache 15 | dist 16 | .idea 17 | build/ 18 | .env* 19 | .cache* 20 | .serverless 21 | .serverless_nextjs 22 | .serverless_plugins 23 | env.js 24 | tmp 25 | package-lock.json 26 | yarn.lock 27 | test 28 | -------------------------------------------------------------------------------- /templates/aws-dynamodb-starter/serverless.template.yml: -------------------------------------------------------------------------------- 1 | name: aws-dynamodb-starter 2 | org: serverlessinc 3 | description: Deploys a serverless NoSQL database powered by AWS DynamoDB 4 | keywords: aws, serverless, nosql, database 5 | repo: https://github.com/serverless-components/aws-dynamodb 6 | license: MIT -------------------------------------------------------------------------------- /templates/aws-dynamodb-starter/serverless.yml: -------------------------------------------------------------------------------- 1 | name: aws-dynamodb-starter 2 | component: aws-dynamodb 3 | org: serverlessinc 4 | 5 | inputs: 6 | deletionPolicy: delete # allows table to be removed. This property is a safe guard. 7 | attributeDefinitions: 8 | - AttributeName: attribute1 9 | AttributeType: S 10 | - AttributeName: attribute2 11 | AttributeType: N 12 | keySchema: 13 | - AttributeName: attribute1 14 | KeyType: HASH 15 | - AttributeName: attribute2 16 | KeyType: RANGE 17 | region: us-east-1 18 | -------------------------------------------------------------------------------- /test/integration.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { sleep, generateId, getCredentials, getServerlessSdk, getTable } = require('./utils'); 4 | 5 | // set enough timeout for deployment to finish 6 | jest.setTimeout(30000); 7 | 8 | const name = `aws-dynamodb-integration-tests-${generateId()}`; 9 | 10 | // the yaml file we're testing against 11 | const instanceYaml = { 12 | org: 'serverlessinc', 13 | app: 'myApp', 14 | component: 'aws-dynamodb@dev', 15 | name, 16 | stage: 'dev', 17 | inputs: { 18 | deletionPolicy: 'delete', 19 | attributeDefinitions: [ 20 | { 21 | AttributeName: 'attribute1', 22 | AttributeType: 'S', 23 | }, 24 | { 25 | AttributeName: 'attribute2', 26 | AttributeType: 'N', 27 | }, 28 | ], 29 | keySchema: [ 30 | { 31 | AttributeName: 'attribute1', 32 | KeyType: 'HASH', 33 | }, 34 | { 35 | AttributeName: 'attribute2', 36 | KeyType: 'RANGE', 37 | }, 38 | ], // local secondary indexes can only be added on table creation 39 | localSecondaryIndexes: [ 40 | { 41 | IndexName: 'myLocalSecondaryIndex', 42 | Projection: { 43 | ProjectionType: 'KEYS_ONLY', 44 | }, 45 | KeySchema: [ 46 | { 47 | AttributeName: 'attribute1', 48 | KeyType: 'HASH', 49 | }, 50 | { 51 | AttributeName: 'attribute2', 52 | KeyType: 'RANGE', 53 | }, 54 | ], 55 | }, 56 | ], 57 | }, 58 | }; 59 | 60 | // get aws credentials from env 61 | const credentials = getCredentials(); 62 | 63 | // get serverless access key from env and construct sdk 64 | const sdk = getServerlessSdk(instanceYaml.org); 65 | 66 | // clean up the instance after tests 67 | afterAll(async () => { 68 | await sdk.remove(instanceYaml, credentials); 69 | }); 70 | 71 | it('should successfully deploy dynamodb table and local index', async () => { 72 | const instance = await sdk.deploy(instanceYaml, credentials); 73 | 74 | await sleep(5000); 75 | 76 | const res = await getTable(credentials, name); 77 | 78 | expect(instance.outputs.name).toBeDefined(); 79 | expect(instance.outputs.arn).toBeDefined(); 80 | expect(res.Table.AttributeDefinitions.length).toEqual(2); 81 | expect(res.Table.KeySchema.length).toEqual(2); 82 | expect(res.Table.LocalSecondaryIndexes.length).toEqual(1); 83 | }); 84 | 85 | // global secondary indexes take really long time to create. 86 | // it causes the test to timeout and the remove operation to fail 87 | // because another process is still in place 88 | 89 | // as a result it 90 | // it.skip('should successfully add global index', async () => { 91 | // instanceYaml.inputs.globalSecondaryIndexes = [ 92 | // { 93 | // IndexName: 'myGlobalSecondaryIndex', 94 | // Projection: { 95 | // ProjectionType: 'KEYS_ONLY' 96 | // }, 97 | // KeySchema: [ 98 | // { 99 | // AttributeName: 'attribute1', 100 | // KeyType: 'HASH' 101 | // }, 102 | // { 103 | // AttributeName: 'attribute2', 104 | // KeyType: 'RANGE' 105 | // } 106 | // ] 107 | // } 108 | // ] 109 | 110 | // await sdk.deploy(instanceYaml, credentials) 111 | 112 | // await sleep(5000) 113 | 114 | // const res = await getTable(credentials, name) 115 | 116 | // expect(res.Table.GlobalSecondaryIndexes.length).toEqual(1) 117 | // }) 118 | 119 | it('should successfully remove dynamodb table', async () => { 120 | await sdk.remove(instanceYaml, credentials); 121 | 122 | await sleep(5000); 123 | 124 | // make sure table was actually removed 125 | let table; 126 | try { 127 | table = await getTable(credentials, name); 128 | } catch (e) { 129 | if (e.code !== 'ResourceNotFoundException') { 130 | throw e; 131 | } 132 | } 133 | 134 | expect(table).toBeUndefined(); 135 | }); 136 | -------------------------------------------------------------------------------- /test/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const AWS = require('aws-sdk'); 5 | const { ServerlessSDK } = require('@serverless/platform-client'); 6 | const dotenv = require('dotenv').config({ path: path.resolve(__dirname, '.env') }).parsed || {}; 7 | 8 | /* 9 | * Pauses execution for an X period of time 10 | */ 11 | const sleep = async (wait) => new Promise((resolve) => setTimeout(() => resolve(), wait)); 12 | 13 | /* 14 | * Generate random id 15 | */ 16 | const generateId = () => Math.random().toString(36).substring(6); 17 | 18 | /* 19 | * Fetches AWS credentials from the current environment 20 | * either from env vars, or .env file in the /test directory 21 | */ 22 | const getCredentials = () => { 23 | const credentials = { 24 | aws: { 25 | accessKeyId: process.env.AWS_ACCESS_KEY_ID || dotenv.AWS_ACCESS_KEY_ID, 26 | secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || dotenv.AWS_SECRET_ACCESS_KEY, 27 | }, 28 | }; 29 | 30 | if (!credentials.aws.accessKeyId || !credentials.aws.accessKeyId) { 31 | throw new Error('Unable to run tests. AWS credentials not found in the envionrment'); 32 | } 33 | 34 | return credentials; 35 | }; 36 | 37 | /* 38 | * Initializes and returns an instance of the serverless sdk 39 | * @param ${string} orgName - the serverless org name. Must correspond to the access key in the env 40 | */ 41 | const getServerlessSdk = (orgName) => { 42 | const sdk = new ServerlessSDK({ 43 | accessKey: process.env.SERVERLESS_ACCESS_KEY || dotenv.SERVERLESS_ACCESS_KEY, 44 | context: { 45 | orgName, 46 | }, 47 | }); 48 | return sdk; 49 | }; 50 | 51 | /* 52 | * Fetches a DynamoDB table from aws for validation 53 | * @param ${object} credentials - the cross provider credentials object 54 | * @param ${string} tableName - the name of the dynamodb table 55 | */ 56 | const getTable = async (credentials, tableName) => { 57 | const config = { 58 | credentials: credentials.aws, 59 | region: 'us-east-1', 60 | }; 61 | const dynamodb = new AWS.DynamoDB(config); 62 | 63 | return dynamodb 64 | .describeTable({ 65 | TableName: tableName, 66 | }) 67 | .promise(); 68 | }; 69 | 70 | module.exports = { sleep, generateId, getCredentials, getServerlessSdk, getTable }; 71 | --------------------------------------------------------------------------------