├── .gitignore ├── .yarn └── releases │ └── yarn-3.1.1.cjs ├── .yarnrc.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── THIRD-PARTY-LICENSES ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── model ├── build.gradle ├── settings.gradle ├── smithy-build.json └── src │ └── main │ └── smithy │ └── main.smithy ├── package.json ├── server ├── .eslintrc.js ├── bin │ └── cdk.ts ├── cdk.json ├── codegen │ ├── build.gradle │ ├── model │ │ └── apigateway.smithy │ ├── settings.gradle │ └── smithy-build.json ├── jest.config.js ├── lib │ └── cdk-stack.ts ├── package.json ├── prettier.config.js ├── src │ ├── apigateway.ts │ ├── echo.spec.ts │ ├── echo.ts │ ├── echo_handler.ts │ ├── length.spec.ts │ ├── length.ts │ ├── length_handler.ts │ └── util.ts └── tsconfig.json ├── settings.gradle ├── typescript-client ├── bin │ └── length.ts ├── codegen │ ├── build.gradle │ ├── settings.gradle │ └── smithy-build.json ├── package.json └── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | **/node_modules/ 2 | **/build/ 3 | **/dist/ 4 | **/.gradle/ 5 | /server/cdk.out/ 6 | /.yarn/install-state.gz 7 | /server/.aws-sam/ 8 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | enableGlobalCache: true 2 | 3 | nodeLinker: node-modules 4 | 5 | yarnPath: .yarn/releases/yarn-3.1.1.cjs 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Smithy Server Generator for TypeScript Example Service 2 | 3 | ### Overview 4 | 5 | This repository is divided into three projects: 6 | 7 | - `model` contains the Smithy model for the service. 8 | - `typescript-client` contains the generated TypeScript client generated from `model`. 9 | - `server` contains the service, written in TypeScript, for `model`. 10 | 11 | ### Building 12 | 13 | #### Prerequisites 14 | 15 | Before beginning: 16 | - Install 17 | - [JDK](https://aws.amazon.com/corretto/) >= 8 18 | - [NodeJS](https://nodejs.org/en/download/) >= 14 19 | - [AWS CDK CLI](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) 20 | - Enable [corepack](https://nodejs.org/api/corepack.html#enabling-the-feature) by running `corepack enable` 21 | - Set up an [AWS account](https://portal.aws.amazon.com/billing/signup) if you do not have one 22 | - [Configure your workstation](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites) 23 | so the CDK can use your account 24 | 25 | ### Getting started 26 | 27 | 1. After the first checkout, you will need to kick off the initial code generation and build by running: 28 | ```bash 29 | ./gradlew build && yarn install && yarn build 30 | ``` 31 | After this initial build, `yarn build` in the root of the project will regenerate the client and server and recompile 32 | all of the code. 33 | 2. To deploy the service, switch to the `server` directory and run `cdk deploy`. When complete, the CDK will print out the endpoint URL 34 | for your newly deployed service. 35 | > Note: this step will create resources in your AWS account that may incur charges. 36 | 3. To test your service, switch to the `typescript-client` directory and use `yarn str-length` to call the `Length` 37 | operation. For example, given an output from the CDK of 38 | `https://somerandomstring.execute-api.us-west-2.amazonaws.com/prod/`, 39 | ```bash 40 | yarn str-length https://somerandomstring.execute-api.us-west-2.amazonaws.com/prod/ foobar 41 | ``` 42 | should print out `6`. 43 | 44 | ## Security 45 | 46 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 47 | 48 | ## License 49 | 50 | This library is licensed under the MIT-0 License. See the LICENSE file. 51 | 52 | -------------------------------------------------------------------------------- /THIRD-PARTY-LICENSES: -------------------------------------------------------------------------------- 1 | ** Gradle; version 7.2 -- https://gradle.org/ 2 | 3 | 4 | Apache License 5 | Version 2.0, January 2004 6 | http://www.apache.org/licenses/ 7 | 8 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 9 | 10 | 1. Definitions. 11 | 12 | "License" shall mean the terms and conditions for use, reproduction, 13 | and distribution as defined by Sections 1 through 9 of this document. 14 | 15 | "Licensor" shall mean the copyright owner or entity authorized by 16 | the copyright owner that is granting the License. 17 | 18 | "Legal Entity" shall mean the union of the acting entity and all 19 | other entities that control, are controlled by, or are under common 20 | control with that entity. For the purposes of this definition, 21 | "control" means (i) the power, direct or indirect, to cause the 22 | direction or management of such entity, whether by contract or 23 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 24 | outstanding shares, or (iii) beneficial ownership of such entity. 25 | 26 | "You" (or "Your") shall mean an individual or Legal Entity 27 | exercising permissions granted by this License. 28 | 29 | "Source" form shall mean the preferred form for making modifications, 30 | including but not limited to software source code, documentation 31 | source, and configuration files. 32 | 33 | "Object" form shall mean any form resulting from mechanical 34 | transformation or translation of a Source form, including but 35 | not limited to compiled object code, generated documentation, 36 | and conversions to other media types. 37 | 38 | "Work" shall mean the work of authorship, whether in Source or 39 | Object form, made available under the License, as indicated by a 40 | copyright notice that is included in or attached to the work 41 | (an example is provided in the Appendix below). 42 | 43 | "Derivative Works" shall mean any work, whether in Source or Object 44 | form, that is based on (or derived from) the Work and for which the 45 | editorial revisions, annotations, elaborations, or other modifications 46 | represent, as a whole, an original work of authorship. For the purposes 47 | of this License, Derivative Works shall not include works that remain 48 | separable from, or merely link (or bind by name) to the interfaces of, 49 | the Work and Derivative Works thereof. 50 | 51 | "Contribution" shall mean any work of authorship, including 52 | the original version of the Work and any modifications or additions 53 | to that Work or Derivative Works thereof, that is intentionally 54 | submitted to Licensor for inclusion in the Work by the copyright owner 55 | or by an individual or Legal Entity authorized to submit on behalf of 56 | the copyright owner. For the purposes of this definition, "submitted" 57 | means any form of electronic, verbal, or written communication sent 58 | to the Licensor or its representatives, including but not limited to 59 | communication on electronic mailing lists, source code control systems, 60 | and issue tracking systems that are managed by, or on behalf of, the 61 | Licensor for the purpose of discussing and improving the Work, but 62 | excluding communication that is conspicuously marked or otherwise 63 | designated in writing by the copyright owner as "Not a Contribution." 64 | 65 | "Contributor" shall mean Licensor and any individual or Legal Entity 66 | on behalf of whom a Contribution has been received by Licensor and 67 | subsequently incorporated within the Work. 68 | 69 | 2. Grant of Copyright License. Subject to the terms and conditions of 70 | this License, each Contributor hereby grants to You a perpetual, 71 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 72 | copyright license to reproduce, prepare Derivative Works of, 73 | publicly display, publicly perform, sublicense, and distribute the 74 | Work and such Derivative Works in Source or Object form. 75 | 76 | 3. Grant of Patent License. Subject to the terms and conditions of 77 | this License, each Contributor hereby grants to You a perpetual, 78 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 79 | (except as stated in this section) patent license to make, have made, 80 | use, offer to sell, sell, import, and otherwise transfer the Work, 81 | where such license applies only to those patent claims licensable 82 | by such Contributor that are necessarily infringed by their 83 | Contribution(s) alone or by combination of their Contribution(s) 84 | with the Work to which such Contribution(s) was submitted. If You 85 | institute patent litigation against any entity (including a 86 | cross-claim or counterclaim in a lawsuit) alleging that the Work 87 | or a Contribution incorporated within the Work constitutes direct 88 | or contributory patent infringement, then any patent licenses 89 | granted to You under this License for that Work shall terminate 90 | as of the date such litigation is filed. 91 | 92 | 4. Redistribution. You may reproduce and distribute copies of the 93 | Work or Derivative Works thereof in any medium, with or without 94 | modifications, and in Source or Object form, provided that You 95 | meet the following conditions: 96 | 97 | (a) You must give any other recipients of the Work or 98 | Derivative Works a copy of this License; and 99 | 100 | (b) You must cause any modified files to carry prominent notices 101 | stating that You changed the files; and 102 | 103 | (c) You must retain, in the Source form of any Derivative Works 104 | that You distribute, all copyright, patent, trademark, and 105 | attribution notices from the Source form of the Work, 106 | excluding those notices that do not pertain to any part of 107 | the Derivative Works; and 108 | 109 | (d) If the Work includes a "NOTICE" text file as part of its 110 | distribution, then any Derivative Works that You distribute must 111 | include a readable copy of the attribution notices contained 112 | within such NOTICE file, excluding those notices that do not 113 | pertain to any part of the Derivative Works, in at least one 114 | of the following places: within a NOTICE text file distributed 115 | as part of the Derivative Works; within the Source form or 116 | documentation, if provided along with the Derivative Works; or, 117 | within a display generated by the Derivative Works, if and 118 | wherever such third-party notices normally appear. The contents 119 | of the NOTICE file are for informational purposes only and 120 | do not modify the License. You may add Your own attribution 121 | notices within Derivative Works that You distribute, alongside 122 | or as an addendum to the NOTICE text from the Work, provided 123 | that such additional attribution notices cannot be construed 124 | as modifying the License. 125 | 126 | You may add Your own copyright statement to Your modifications and 127 | may provide additional or different license terms and conditions 128 | for use, reproduction, or distribution of Your modifications, or 129 | for any such Derivative Works as a whole, provided Your use, 130 | reproduction, and distribution of the Work otherwise complies with 131 | the conditions stated in this License. 132 | 133 | 5. Submission of Contributions. Unless You explicitly state otherwise, 134 | any Contribution intentionally submitted for inclusion in the Work 135 | by You to the Licensor shall be under the terms and conditions of 136 | this License, without any additional terms or conditions. 137 | Notwithstanding the above, nothing herein shall supersede or modify 138 | the terms of any separate license agreement you may have executed 139 | with Licensor regarding such Contributions. 140 | 141 | 6. Trademarks. This License does not grant permission to use the trade 142 | names, trademarks, service marks, or product names of the Licensor, 143 | except as required for reasonable and customary use in describing the 144 | origin of the Work and reproducing the content of the NOTICE file. 145 | 146 | 7. Disclaimer of Warranty. Unless required by applicable law or 147 | agreed to in writing, Licensor provides the Work (and each 148 | Contributor provides its Contributions) on an "AS IS" BASIS, 149 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 150 | implied, including, without limitation, any warranties or conditions 151 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 152 | PARTICULAR PURPOSE. You are solely responsible for determining the 153 | appropriateness of using or redistributing the Work and assume any 154 | risks associated with Your exercise of permissions under this License. 155 | 156 | 8. Limitation of Liability. In no event and under no legal theory, 157 | whether in tort (including negligence), contract, or otherwise, 158 | unless required by applicable law (such as deliberate and grossly 159 | negligent acts) or agreed to in writing, shall any Contributor be 160 | liable to You for damages, including any direct, indirect, special, 161 | incidental, or consequential damages of any character arising as a 162 | result of this License or out of the use or inability to use the 163 | Work (including but not limited to damages for loss of goodwill, 164 | work stoppage, computer failure or malfunction, or any and all 165 | other commercial damages or losses), even if such Contributor 166 | has been advised of the possibility of such damages. 167 | 168 | 9. Accepting Warranty or Additional Liability. While redistributing 169 | the Work or Derivative Works thereof, You may choose to offer, 170 | and charge a fee for, acceptance of support, warranty, indemnity, 171 | or other liability obligations and/or rights consistent with this 172 | License. However, in accepting such obligations, You may act only 173 | on Your own behalf and on Your sole responsibility, not on behalf 174 | of any other Contributor, and only if You agree to indemnify, 175 | defend, and hold each Contributor harmless for any liability 176 | incurred by, or claims asserted against, such Contributor by reason 177 | of your accepting any such warranty or additional liability. 178 | 179 | END OF TERMS AND CONDITIONS 180 | * For Gradle see also this required NOTICE: 181 | Copyright 2007 the original author or authors. 182 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/smithy-server-generator-typescript-sample/1df8a4e6716761e5efda60edce27361b3e8e3760/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /model/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://aws.amazon.com/apache2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | 16 | buildscript { 17 | repositories { 18 | mavenCentral() 19 | } 20 | dependencies { 21 | classpath "software.amazon.smithy:smithy-cli:1.19.0" 22 | } 23 | } 24 | 25 | plugins { 26 | id 'software.amazon.smithy' version '0.6.0' 27 | id 'maven-publish' 28 | } 29 | 30 | group = 'software.amazon.smithy.demo' 31 | version = '1.0-SNAPSHOT' 32 | 33 | repositories { 34 | mavenLocal() 35 | mavenCentral() 36 | } 37 | 38 | dependencies { 39 | implementation 'software.amazon.smithy:smithy-model:1.19.0' 40 | implementation 'software.amazon.smithy:smithy-aws-traits:1.19.0' 41 | implementation 'software.amazon.smithy:smithy-validation-model:1.19.0' 42 | } 43 | 44 | publishing { 45 | publications { 46 | maven(MavenPublication) { 47 | from components.java 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /model/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'string-wizard-model' 2 | -------------------------------------------------------------------------------- /model/smithy-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "version" : "1.0" 3 | } 4 | -------------------------------------------------------------------------------- /model/src/main/smithy/main.smithy: -------------------------------------------------------------------------------- 1 | namespace software.amazon.smithy.demo 2 | 3 | use aws.auth#sigv4 4 | use aws.protocols#restJson1 5 | use smithy.framework#ValidationException 6 | 7 | @title("A magical string manipulation service") 8 | 9 | // Cross-origin resource sharing allows resources to be requested from external domains. 10 | // Cors should be enabled for externally facing services and disabled for internally facing services. 11 | // Enabling cors will modify the OpenAPI spec used to define your API Gateway endpoint. 12 | // Uncomment the line below to enable cross-origin resource sharing 13 | // @cors() 14 | 15 | @sigv4(name: "execute-api") 16 | @restJson1 17 | service StringWizard { 18 | version: "2018-05-10", 19 | operations: [Echo, Length], 20 | } 21 | 22 | /// Echo operation that receives input from body. 23 | @http(code: 200, method: "POST", uri: "/echo",) 24 | operation Echo { 25 | input: EchoInput, 26 | output: EchoOutput, 27 | errors: [ValidationException, PalindromeException], 28 | } 29 | 30 | /// Length operation that receives input from path. 31 | @readonly 32 | @http(code: 200, method: "GET", uri: "/length/{string}",) 33 | operation Length { 34 | input: LengthInput, 35 | output: LengthOutput, 36 | errors: [ValidationException, PalindromeException], 37 | } 38 | 39 | structure EchoInput { 40 | string: String, 41 | } 42 | 43 | structure EchoOutput { 44 | string: String, 45 | } 46 | 47 | structure LengthInput { 48 | @required 49 | @httpLabel 50 | string: String, 51 | } 52 | 53 | structure LengthOutput { 54 | length: Integer, 55 | } 56 | 57 | /// For some reason, this service does not like palindromes! 58 | @httpError(400) 59 | @error("client") 60 | structure PalindromeException { 61 | message: String, 62 | } 63 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "string-service-build", 3 | "version": "0.0.1", 4 | "description": "A yarn project for the string service monorepo", 5 | "packageManager": "yarn@3.1.1", 6 | "author": "", 7 | "license": "Apache-2.0", 8 | "private": true, 9 | "scripts": { 10 | "generate": "./gradlew clean build", 11 | "build:client": "cd typescript-client && yarn build", 12 | "build:server": "cd server && yarn build", 13 | "build": "yarn generate && yarn build:client && yarn build:server" 14 | }, 15 | "devDependencies": { 16 | "esbuild": "^0.14.27", 17 | "rimraf": "^3.0.0" 18 | }, 19 | "workspaces": [ 20 | "typescript-client", 21 | "server" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /server/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: "@typescript-eslint/parser", // Specifies the ESLint parser 3 | parserOptions: { 4 | ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features 5 | sourceType: "module", // Allows for the use of imports 6 | }, 7 | extends: [ 8 | // Uses the recommended rules from the @typescript-eslint/eslint-plugin 9 | "plugin:@typescript-eslint/recommended", 10 | ], 11 | plugins: ["@typescript-eslint", "simple-import-sort"], 12 | rules: { 13 | /** Turn off strict enforcement */ 14 | "@typescript-eslint/ban-types": "off", 15 | "@typescript-eslint/ban-ts-comment": "off", 16 | "@typescript-eslint/no-var-requires": "off", 17 | "@typescript-eslint/no-empty-function": "off", 18 | "@typescript-eslint/no-empty-interface": "off", 19 | "@typescript-eslint/no-explicit-any": "off", 20 | "@typescript-eslint/explicit-module-boundary-types": "off", 21 | "prefer-rest-params": "off", 22 | "@typescript-eslint/no-non-null-assertion": "off", 23 | 24 | /** Warnings */ 25 | "@typescript-eslint/no-namespace": "warn", 26 | 27 | /** Errors */ 28 | "simple-import-sort/imports": "error", 29 | }, 30 | }; 31 | -------------------------------------------------------------------------------- /server/bin/cdk.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import "source-map-support/register"; 3 | 4 | import * as cdk from "aws-cdk-lib"; 5 | 6 | import { CdkStack } from "../lib/cdk-stack"; 7 | 8 | const app = new cdk.App(); 9 | new CdkStack(app, "StringWizardService", { 10 | /* If you don't specify 'env', this stack will be environment-agnostic. 11 | * Account/Region-dependent features and context lookups will not work, 12 | * but a single synthesized template can be deployed anywhere. */ 13 | 14 | /* Uncomment the next line to specialize this stack for the AWS Account 15 | * and Region that are implied by the current CLI configuration. */ 16 | // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, 17 | 18 | /* Uncomment the next line if you know exactly what Account and Region you 19 | * want to deploy the stack to. */ 20 | env: { 21 | account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, 22 | region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION, 23 | }, 24 | 25 | /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */ 26 | }); 27 | -------------------------------------------------------------------------------- /server/cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "npx ts-node --prefer-ts-exts bin/cdk.ts", 3 | "context": { 4 | "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, 5 | "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, 6 | "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, 7 | "@aws-cdk/core:stackRelativeExports": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /server/codegen/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://aws.amazon.com/apache2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | 16 | import software.amazon.smithy.gradle.tasks.SmithyBuild 17 | 18 | buildscript { 19 | repositories { 20 | mavenLocal() 21 | mavenCentral() 22 | } 23 | dependencies { 24 | classpath 'software.amazon.smithy.demo:string-wizard-model:1.0-SNAPSHOT' 25 | classpath 'software.amazon.smithy.typescript:smithy-typescript-codegen:0.11.0' 26 | classpath 'software.amazon.smithy.typescript:smithy-aws-typescript-codegen:0.11.0' 27 | classpath "software.amazon.smithy:smithy-model:1.19.0" 28 | classpath "software.amazon.smithy:smithy-openapi:1.19.0" 29 | classpath "software.amazon.smithy:smithy-aws-traits:1.19.0" 30 | classpath "software.amazon.smithy:smithy-aws-apigateway-openapi:1.19.0" 31 | classpath "software.amazon.smithy:smithy-cli:1.19.0" 32 | } 33 | } 34 | 35 | plugins { 36 | id 'software.amazon.smithy' 37 | } 38 | 39 | dependencies { 40 | implementation "software.amazon.smithy:smithy-aws-traits:1.19.0" 41 | implementation "software.amazon.smithy:smithy-aws-apigateway-openapi:1.19.0" 42 | implementation 'software.amazon.smithy.demo:string-wizard-model:1.0-SNAPSHOT' 43 | } 44 | 45 | repositories { 46 | mavenLocal() 47 | mavenCentral() 48 | } 49 | 50 | jar.enabled = false 51 | smithyBuildJar.enabled = false 52 | 53 | task generateServer(type: SmithyBuild) {} 54 | 55 | build.dependsOn generateServer 56 | -------------------------------------------------------------------------------- /server/codegen/model/apigateway.smithy: -------------------------------------------------------------------------------- 1 | namespace software.amazon.smithy.demo 2 | 3 | apply Echo @aws.apigateway#integration( 4 | type: "aws_proxy", 5 | httpMethod: "POST", 6 | uri: "" 7 | ) 8 | 9 | apply Length @aws.apigateway#integration( 10 | type: "aws_proxy", 11 | httpMethod: "POST", 12 | uri: "" 13 | ) 14 | -------------------------------------------------------------------------------- /server/codegen/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'server-codegen' 2 | -------------------------------------------------------------------------------- /server/codegen/smithy-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "version" : "1.0", 3 | "outputDirectory" : "build/output", 4 | "projections" : { 5 | "ts-server" : { 6 | "plugins": { 7 | "typescript-ssdk-codegen" : { 8 | "package" : "@smithy-demo/string-wizard-service-ssdk", 9 | "packageVersion": "0.0.1" 10 | } 11 | } 12 | }, 13 | "apigateway" : { 14 | "imports" : ["model/"], 15 | "plugins" : { 16 | "openapi": { 17 | "service": "software.amazon.smithy.demo#StringWizard", 18 | "protocol": "aws.protocols#restJson1", 19 | "apiGatewayType" : "REST" 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /server/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: "ts-jest", 3 | modulePathIgnorePatterns: ["/codegen/"] 4 | }; 5 | -------------------------------------------------------------------------------- /server/lib/cdk-stack.ts: -------------------------------------------------------------------------------- 1 | import { StringWizardServiceOperations } from "@smithy-demo/string-wizard-service-ssdk"; 2 | import * as cdk from "aws-cdk-lib"; 3 | import { 4 | AccessLogFormat, 5 | ApiDefinition, 6 | LogGroupLogDestination, 7 | MethodLoggingLevel, 8 | SpecRestApi, 9 | } from "aws-cdk-lib/aws-apigateway"; 10 | import { AnyPrincipal, Effect, PolicyDocument, PolicyStatement, ServicePrincipal } from "aws-cdk-lib/aws-iam"; 11 | import {Runtime} from "aws-cdk-lib/aws-lambda"; 12 | import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"; 13 | import { LogGroup } from "aws-cdk-lib/aws-logs"; 14 | import { Construct } from "constructs"; 15 | import { readFileSync } from "fs"; 16 | import * as path from "path"; 17 | 18 | export class CdkStack extends cdk.Stack { 19 | constructor(scope: Construct, id: string, props?: cdk.StackProps) { 20 | super(scope, id, props); 21 | 22 | const logGroup = new LogGroup(this, "ApiLogs"); 23 | 24 | const entry_points: { [op in StringWizardServiceOperations]: string } = { 25 | Echo: "echo_handler", 26 | Length: "length_handler", 27 | }; 28 | 29 | const functions = (Object.keys(entry_points) as StringWizardServiceOperations[]).reduce( 30 | (acc, operation) => ({ 31 | ...acc, 32 | [operation]: new NodejsFunction(this, operation + "Function", { 33 | entry: path.join(__dirname, `../dist/src/${entry_points[operation]}.js`), 34 | handler: "lambdaHandler", 35 | runtime: Runtime.NODEJS_18_X, 36 | bundling: { 37 | minify: true, 38 | tsconfig: path.join(__dirname, "../tsconfig.json"), 39 | // re2-wasm is used by the SSDK common library to do pattern validation, and uses 40 | // a WASM module, so it's excluded from the bundle 41 | nodeModules: ["re2-wasm"], 42 | 43 | // Enable these for easier debugging, though they will increase your artifact size 44 | // sourceMap: true, 45 | // sourceMapMode: SourceMapMode.INLINE 46 | }, 47 | }), 48 | }), 49 | {} 50 | ) as { [op in StringWizardServiceOperations]: NodejsFunction }; 51 | 52 | const api = new SpecRestApi(this, "StringWizardApi", { 53 | apiDefinition: ApiDefinition.fromInline(this.getOpenApiDef(functions)), 54 | deploy: true, 55 | deployOptions: { 56 | accessLogDestination: new LogGroupLogDestination(logGroup), 57 | accessLogFormat: AccessLogFormat.jsonWithStandardFields(), 58 | loggingLevel: MethodLoggingLevel.INFO, 59 | dataTraceEnabled: true, 60 | metricsEnabled: true, 61 | }, 62 | policy: new PolicyDocument({ 63 | statements: [ 64 | new PolicyStatement({ 65 | effect: Effect.ALLOW, 66 | principals: [new AnyPrincipal()], 67 | actions: ["execute-api:Invoke"], 68 | resources: ["execute-api:/*/*/*"], 69 | }), 70 | ], 71 | }), 72 | }); 73 | 74 | for (const [k, v] of Object.entries(functions)) { 75 | v.addPermission(`${k}Permission`, { 76 | principal: new ServicePrincipal("apigateway.amazonaws.com"), 77 | sourceArn: `arn:${this.partition}:execute-api:${this.region}:${this.account}:${api.restApiId}/*/*/*`, 78 | }); 79 | } 80 | } 81 | 82 | private getOpenApiDef(functions: { [op in StringWizardServiceOperations]?: NodejsFunction }) { 83 | const openapi = JSON.parse( 84 | readFileSync( 85 | path.join(__dirname, "../codegen/build/smithyprojections/server-codegen/apigateway/openapi/StringWizard.openapi.json"), 86 | "utf8" 87 | ) 88 | ); 89 | for (const path in openapi.paths) { 90 | for (const operation in openapi.paths[path]) { 91 | const op = openapi.paths[path][operation]; 92 | const integration = op["x-amazon-apigateway-integration"]; 93 | // Don't try to mess with mock integrations 94 | if (integration !== null && integration !== undefined && integration["type"] === "mock") { 95 | continue; 96 | } 97 | const functionArn = functions[op.operationId as StringWizardServiceOperations]?.functionArn; 98 | if (functionArn === null || functionArn === undefined) { 99 | throw new Error("no function for " + op.operationId); 100 | } 101 | if (!op["x-amazon-apigateway-integration"]) { 102 | throw new Error( 103 | `No x-amazon-apigateway-integration for ${op.operationId}. Make sure API Gateway integration is configured in codegen/model/apigateway.smithy` 104 | ); 105 | } 106 | op[ 107 | "x-amazon-apigateway-integration" 108 | ].uri = `arn:${this.partition}:apigateway:${this.region}:lambda:path/2015-03-31/functions/${functionArn}/invocations`; 109 | } 110 | } 111 | return openapi; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "string-server", 3 | "version": "0.0.1", 4 | "description": "The server for StringWizard service", 5 | "packageManager": "yarn@3.1.1", 6 | "author": "", 7 | "license": "Apache-2.0", 8 | "private": true, 9 | "scripts": { 10 | "clean": "rimraf dist", 11 | "pretest": "yarn build", 12 | "test": "jest", 13 | "generate-ssdk": "cd ../ && ./gradlew :server-codegen:build", 14 | "build:ssdk": "cd codegen/build/smithyprojections/server-codegen/ts-server/typescript-ssdk-codegen && yarn install && yarn build", 15 | "regenerate:ssdk": "yarn generate-ssdk && yarn build:ssdk", 16 | "build": "yarn regenerate:ssdk && tsc && jest", 17 | "prepare": "cd .. && husky install server/.husky" 18 | }, 19 | "files": [ 20 | "dist" 21 | ], 22 | "dependencies": { 23 | "@aws-smithy/server-apigateway": "^1.0.0-alpha.5", 24 | "@aws-smithy/server-common": "^1.0.0-alpha.5", 25 | "@smithy-demo/string-wizard-service-ssdk": "workspace:server/codegen/build/smithyprojections/server-codegen/ts-server/typescript-ssdk-codegen", 26 | "@types/aws-lambda": "^8.10.85" 27 | }, 28 | "devDependencies": { 29 | "@aws-cdk/assert": "^2.1.0", 30 | "@tsconfig/node14": "^1.0.1", 31 | "@types/jest": "^26.0.24", 32 | "@typescript-eslint/eslint-plugin": "^5.6.0", 33 | "@typescript-eslint/parser": "^5.6.0", 34 | "aws-cdk-lib": "^2.67.0", 35 | "constructs": "^10.0.0", 36 | "eslint": "7.32.0", 37 | "eslint-config-prettier": "8.3.0", 38 | "eslint-plugin-prettier": "3.4.1", 39 | "eslint-plugin-simple-import-sort": "7.0.0", 40 | "eslint-plugin-sort-export-all": "1.1.1", 41 | "husky": "^7.0.4", 42 | "jest": "^29.4.3", 43 | "lint-staged": "^12.1.2", 44 | "prettier": "2.3.0", 45 | "rimraf": "^3.0.0", 46 | "ts-jest": "^29.0.5", 47 | "typescript": "~4.6.2" 48 | }, 49 | "lint-staged": { 50 | "*.(js|ts)": [ 51 | "eslint --cache --fix", 52 | "prettier --write" 53 | ], 54 | "*.(md|json)": [ 55 | "prettier --write" 56 | ] 57 | }, 58 | "workspaces": [ 59 | "codegen/build/smithyprojections/server-codegen/ts-server/typescript-ssdk-codegen" 60 | ] 61 | } 62 | -------------------------------------------------------------------------------- /server/prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // Custom 3 | printWidth: 120, 4 | }; 5 | -------------------------------------------------------------------------------- /server/src/apigateway.ts: -------------------------------------------------------------------------------- 1 | import { convertEvent, convertVersion1Response } from "@aws-smithy/server-apigateway"; 2 | import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"; 3 | import { ServiceHandler } from "@aws-smithy/server-common"; 4 | import { APIGatewayProxyHandler } from "aws-lambda/trigger/api-gateway-proxy"; 5 | 6 | /** 7 | * Defines anything the operation handler needs that is not modeled in the operation's Smithy model but comes from 8 | * other context 9 | */ 10 | export interface HandlerContext { 11 | user: string; 12 | } 13 | 14 | /** 15 | * Given a ServiceHandler, returns an APIGatewayProxyHandler that knows how to: 16 | * 1. convert the APIGateway request (APIGatewayProxyEvent) into inputs for the ServiceHandler 17 | * 2. invoke the ServiceHandler 18 | * 3. convert the output of ServiceHandler into the result (APIGatewayProxyResult) expected by APIGateway 19 | */ 20 | export function getApiGatewayHandler(handler: ServiceHandler): APIGatewayProxyHandler { 21 | return async (event: APIGatewayProxyEvent): Promise => { 22 | // Extract anything from the APIGateway requestContext that you'd need in your operation handler 23 | const userArn = event.requestContext.identity.userArn; 24 | if (!userArn) { 25 | throw new Error("IAM Auth is not enabled"); 26 | } 27 | const context = { user: userArn }; 28 | 29 | const httpRequest = convertEvent(event); 30 | const httpResponse = await handler.handle(httpRequest, context); 31 | return convertVersion1Response(httpResponse); 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /server/src/echo.spec.ts: -------------------------------------------------------------------------------- 1 | import { EchoOperation } from "./echo"; 2 | import { PalindromeException } from "@smithy-demo/string-wizard-service-ssdk"; 3 | 4 | describe("Echo tests", () => { 5 | const context = { user: "user123" }; 6 | 7 | it("echoes the string back", async () => { 8 | const output = await EchoOperation({ string: "canoe" }, context); 9 | expect(output.string).toBe("canoe"); 10 | }); 11 | 12 | it("handles undefined", async () => { 13 | const output = await EchoOperation({}, context); 14 | expect(output.string).toBeUndefined(); 15 | }); 16 | 17 | it("throws on palindrome", async () => { 18 | expect.assertions(1); 19 | try { 20 | await EchoOperation({ string: "kayak" }, context); 21 | } catch (e) { 22 | expect(e).toBeInstanceOf(PalindromeException); 23 | } 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /server/src/echo.ts: -------------------------------------------------------------------------------- 1 | import { Operation } from "@aws-smithy/server-common"; 2 | import { EchoServerInput, EchoServerOutput, PalindromeException } from "@smithy-demo/string-wizard-service-ssdk"; 3 | import { HandlerContext } from "./apigateway"; 4 | import { reverse } from "./util"; 5 | 6 | // This is the implementation of business logic of the EchoOperation 7 | export const EchoOperation: Operation = async (input, context) => { 8 | console.log(`Received Echo operation from: ${context.user}`); 9 | 10 | if (input.string != undefined && input.string === reverse(input.string)) { 11 | throw new PalindromeException({ message: "Cannot handle palindrome" }); 12 | } 13 | 14 | return { 15 | string: input.string, 16 | }; 17 | }; 18 | -------------------------------------------------------------------------------- /server/src/echo_handler.ts: -------------------------------------------------------------------------------- 1 | import { getEchoHandler } from "@smithy-demo/string-wizard-service-ssdk"; 2 | import { APIGatewayProxyHandler } from "aws-lambda"; 3 | import { EchoOperation } from "./echo"; 4 | import { getApiGatewayHandler } from "./apigateway"; 5 | 6 | // This is the entry point for the Lambda Function that services the EchoOperation 7 | export const lambdaHandler: APIGatewayProxyHandler = getApiGatewayHandler(getEchoHandler(EchoOperation)); 8 | -------------------------------------------------------------------------------- /server/src/length.spec.ts: -------------------------------------------------------------------------------- 1 | import { LengthOperation } from "./length"; 2 | import { PalindromeException } from "@smithy-demo/string-wizard-service-ssdk"; 3 | 4 | describe("Length tests", () => { 5 | const context = { user: "user123" }; 6 | 7 | it("returns the length of the string", async () => { 8 | const output = await LengthOperation({ string: "canoe" }, context); 9 | expect(output.length).toBe(5); 10 | }); 11 | 12 | it("handles undefined", async () => { 13 | const output = await LengthOperation({ string: undefined }, context); 14 | expect(output.length).toBeUndefined(); 15 | }); 16 | 17 | it("throws on palindrome", async () => { 18 | expect.assertions(1); 19 | try { 20 | await LengthOperation({ string: "kayak" }, context); 21 | } catch (e) { 22 | expect(e).toBeInstanceOf(PalindromeException); 23 | } 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /server/src/length.ts: -------------------------------------------------------------------------------- 1 | import { Operation } from "@aws-smithy/server-common"; 2 | import { 3 | LengthServerInput, 4 | LengthServerOutput, 5 | PalindromeException, 6 | } from "@smithy-demo/string-wizard-service-ssdk"; 7 | import { HandlerContext } from "./apigateway"; 8 | import { reverse } from "./util"; 9 | 10 | // This is the implementation of business logic of the LengthOperation 11 | export const LengthOperation: Operation = async ( 12 | input, 13 | context 14 | ) => { 15 | console.log(`Received Length operation from: ${context.user}`); 16 | 17 | if (input.string != undefined && input.string === reverse(input.string)) { 18 | throw new PalindromeException({ message: "Cannot handle palindrome" }); 19 | } 20 | 21 | return { 22 | length: input.string?.length, 23 | }; 24 | }; 25 | -------------------------------------------------------------------------------- /server/src/length_handler.ts: -------------------------------------------------------------------------------- 1 | import { getLengthHandler } from "@smithy-demo/string-wizard-service-ssdk"; 2 | import { APIGatewayProxyHandler } from "aws-lambda"; 3 | import { LengthOperation } from "./length"; 4 | import { getApiGatewayHandler } from "./apigateway"; 5 | 6 | // This is the entry point for the Lambda Function that services the LengthOperation 7 | export const lambdaHandler: APIGatewayProxyHandler = getApiGatewayHandler(getLengthHandler(LengthOperation)); 8 | -------------------------------------------------------------------------------- /server/src/util.ts: -------------------------------------------------------------------------------- 1 | // naive implementation for illustration purposes 2 | export function reverse(str: string) { 3 | return str.split("").reverse().join(""); 4 | } 5 | -------------------------------------------------------------------------------- /server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node14/tsconfig.json", 3 | "compilerOptions": { 4 | "resolveJsonModule": true, 5 | "incremental": true, 6 | "noFallthroughCasesInSwitch": true, 7 | "baseUrl": ".", 8 | "outDir": "./dist" 9 | }, 10 | "exclude": ["node_modules/", "**/*.spec.ts"], 11 | "include": ["src/", "lib/", "bin/"] 12 | } 13 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | plugins { 3 | id 'software.amazon.smithy' version '0.6.0' 4 | } 5 | } 6 | 7 | rootProject.name = 'string-wizard-service' 8 | 9 | includeBuild('./model') 10 | 11 | include 'server-codegen' 12 | project(':server-codegen').projectDir = file('server/codegen') 13 | 14 | include 'typescript-client-codegen' 15 | project(':typescript-client-codegen').projectDir = file('typescript-client/codegen') 16 | -------------------------------------------------------------------------------- /typescript-client/bin/length.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import {LengthCommand, StringWizardClient} from "@smithy-demo/string-client"; 4 | 5 | const client = new StringWizardClient({endpoint: process.argv[2]}); 6 | 7 | client.send(new LengthCommand({ 8 | string: process.argv[3] 9 | })).catch((err) => { 10 | console.log("Failed with error: " + err); 11 | process.exit(1); 12 | }).then((res) => { 13 | process.stderr.write(res.length?.toString() ?? "0"); 14 | }); 15 | 16 | 17 | -------------------------------------------------------------------------------- /typescript-client/codegen/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://aws.amazon.com/apache2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | 16 | import software.amazon.smithy.gradle.tasks.SmithyBuild 17 | 18 | buildscript { 19 | repositories { 20 | mavenLocal() 21 | mavenCentral() 22 | } 23 | dependencies { 24 | classpath 'software.amazon.smithy.demo:string-wizard-model:1.0-SNAPSHOT' 25 | classpath 'software.amazon.smithy.typescript:smithy-typescript-codegen:0.11.0' 26 | classpath 'software.amazon.smithy.typescript:smithy-aws-typescript-codegen:0.11.0' 27 | classpath "software.amazon.smithy:smithy-model:1.19.0" 28 | classpath "software.amazon.smithy:smithy-cli:1.19.0" 29 | } 30 | } 31 | 32 | plugins { 33 | id 'software.amazon.smithy' 34 | } 35 | 36 | dependencies { 37 | implementation 'software.amazon.smithy.demo:string-wizard-model:1.0-SNAPSHOT' 38 | } 39 | 40 | repositories { 41 | mavenLocal() 42 | mavenCentral() 43 | } 44 | 45 | jar.enabled = false 46 | smithyBuildJar.enabled = false 47 | 48 | task generate(type: SmithyBuild) {} 49 | 50 | build.dependsOn generate 51 | -------------------------------------------------------------------------------- /typescript-client/codegen/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'typescript-client-codegen' 2 | -------------------------------------------------------------------------------- /typescript-client/codegen/smithy-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "version" : "1.0", 3 | "outputDirectory" : "build/output", 4 | "projections" : { 5 | "ts-client": { 6 | "plugins": { 7 | "typescript-codegen": { 8 | "package" : "@smithy-demo/string-client", 9 | "packageVersion": "0.0.1" 10 | } 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /typescript-client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "string-wizard-service-client-build", 3 | "version": "0.0.1", 4 | "description": "A yarn project for the StringWizard service TypeScript client build process", 5 | "packageManager": "yarn@3.1.1", 6 | "author": "", 7 | "license": "Apache-2.0", 8 | "private": true, 9 | "scripts": { 10 | "generate": "cd ../ && ./gradlew :typescript-client-codegen:build", 11 | "build:client": "cd codegen/build/smithyprojections/typescript-client-codegen/ts-client/typescript-codegen && yarn install && yarn build", 12 | "build": "yarn generate && yarn build:client && tsc" 13 | }, 14 | "bin": { 15 | "str-length": "./dist/length.js" 16 | }, 17 | "dependencies": { 18 | "@smithy-demo/string-client": "workspace:typescript-client/codegen/build/smithyprojections/typescript-client-codegen/ts-client/typescript-codegen" 19 | }, 20 | "devDependencies": { 21 | "@tsconfig/node12": "^1.0.9", 22 | "rimraf": "^3.0.0", 23 | "typescript": "~4.6.2" 24 | }, 25 | "workspaces": [ 26 | "codegen/build/smithyprojections/typescript-client-codegen/ts-client/typescript-codegen" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /typescript-client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/node12/tsconfig.json", 3 | "compilerOptions": { 4 | "incremental": true, 5 | "noFallthroughCasesInSwitch": true, 6 | "baseUrl": ".", 7 | "outDir": "./dist" 8 | }, 9 | "exclude": ["node_modules/", "**/*.spec.ts"], 10 | "include": ["bin/"] 11 | } 12 | --------------------------------------------------------------------------------