├── .eslintrc.json ├── .gitignore ├── .npmignore ├── .projen └── tasks.json ├── .projenrc.js ├── .versionrc.json ├── LICENSE ├── README.md ├── cdk.json ├── frontend ├── .env ├── .gitignore ├── .npmignore ├── .projen │ └── tasks.json ├── .versionrc.json ├── LICENSE ├── README.md ├── amplifyBase.graphql ├── bin │ ├── generateExports.js │ └── generateStatements.js ├── codegen.yml ├── package.json ├── public │ ├── index.html │ ├── manifest.json │ └── robots.txt ├── react-app-env.d.ts ├── src │ ├── App.css │ ├── App.tsx │ ├── components │ │ ├── posts.tsx │ │ └── todos.tsx │ ├── graphql │ │ ├── mutations.ts │ │ ├── queries.ts │ │ └── subscriptions.ts │ ├── index.css │ ├── index.tsx │ ├── lib │ │ ├── api.ts │ │ └── fetcher.ts │ ├── react-app-env.d.ts │ ├── reportWebVitals.ts │ └── setupTests.ts ├── tsconfig.json ├── version.json └── yarn.lock ├── package-lock.json ├── package.json ├── schema.graphql ├── src ├── lib │ └── demo-stack.ts └── main.ts ├── test └── main.test.ts ├── tsconfig.jest.json ├── tsconfig.json └── version.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "jest": true, 4 | "node": true 5 | }, 6 | "root": true, 7 | "plugins": [ 8 | "@typescript-eslint", 9 | "import" 10 | ], 11 | "parser": "@typescript-eslint/parser", 12 | "parserOptions": { 13 | "ecmaVersion": 2018, 14 | "sourceType": "module", 15 | "project": "./tsconfig.jest.json" 16 | }, 17 | "extends": [ 18 | "plugin:import/typescript" 19 | ], 20 | "settings": { 21 | "import/parsers": { 22 | "@typescript-eslint/parser": [ 23 | ".ts", 24 | ".tsx" 25 | ] 26 | }, 27 | "import/resolver": { 28 | "node": {}, 29 | "typescript": { 30 | "directory": "./tsconfig.json" 31 | } 32 | } 33 | }, 34 | "ignorePatterns": [ 35 | "*.js", 36 | "!.projenrc.js", 37 | "*.d.ts", 38 | "node_modules/", 39 | "*.generated.ts", 40 | "coverage" 41 | ], 42 | "rules": { 43 | "@typescript-eslint/no-require-imports": [ 44 | "error" 45 | ], 46 | "indent": [ 47 | "off" 48 | ], 49 | "@typescript-eslint/indent": [ 50 | "error", 51 | 2 52 | ], 53 | "quotes": [ 54 | "error", 55 | "single", 56 | { 57 | "avoidEscape": true 58 | } 59 | ], 60 | "comma-dangle": [ 61 | "error", 62 | "always-multiline" 63 | ], 64 | "comma-spacing": [ 65 | "error", 66 | { 67 | "before": false, 68 | "after": true 69 | } 70 | ], 71 | "no-multi-spaces": [ 72 | "error", 73 | { 74 | "ignoreEOLComments": false 75 | } 76 | ], 77 | "array-bracket-spacing": [ 78 | "error", 79 | "never" 80 | ], 81 | "array-bracket-newline": [ 82 | "error", 83 | "consistent" 84 | ], 85 | "object-curly-spacing": [ 86 | "error", 87 | "always" 88 | ], 89 | "object-curly-newline": [ 90 | "error", 91 | { 92 | "multiline": true, 93 | "consistent": true 94 | } 95 | ], 96 | "object-property-newline": [ 97 | "error", 98 | { 99 | "allowAllPropertiesOnSameLine": true 100 | } 101 | ], 102 | "keyword-spacing": [ 103 | "error" 104 | ], 105 | "brace-style": [ 106 | "error", 107 | "1tbs", 108 | { 109 | "allowSingleLine": true 110 | } 111 | ], 112 | "space-before-blocks": [ 113 | "error" 114 | ], 115 | "curly": [ 116 | "error", 117 | "multi-line", 118 | "consistent" 119 | ], 120 | "@typescript-eslint/member-delimiter-style": [ 121 | "error" 122 | ], 123 | "import/no-extraneous-dependencies": [ 124 | "error", 125 | { 126 | "devDependencies": [ 127 | "**/build-tools/**", 128 | "**/test/**" 129 | ], 130 | "optionalDependencies": false, 131 | "peerDependencies": true 132 | } 133 | ], 134 | "import/no-unresolved": [ 135 | "error" 136 | ], 137 | "import/order": [ 138 | "warn", 139 | { 140 | "groups": [ 141 | "builtin", 142 | "external" 143 | ], 144 | "alphabetize": { 145 | "order": "asc", 146 | "caseInsensitive": true 147 | } 148 | } 149 | ], 150 | "no-duplicate-imports": [ 151 | "error" 152 | ], 153 | "no-shadow": [ 154 | "off" 155 | ], 156 | "@typescript-eslint/no-shadow": [ 157 | "error" 158 | ], 159 | "key-spacing": [ 160 | "error" 161 | ], 162 | "semi": [ 163 | "error", 164 | "always" 165 | ], 166 | "quote-props": [ 167 | "error", 168 | "consistent-as-needed" 169 | ], 170 | "no-multiple-empty-lines": [ 171 | "error" 172 | ], 173 | "max-len": [ 174 | "error", 175 | { 176 | "code": 150, 177 | "ignoreUrls": true, 178 | "ignoreStrings": true, 179 | "ignoreTemplateLiterals": true, 180 | "ignoreComments": true, 181 | "ignoreRegExpLiterals": true 182 | } 183 | ], 184 | "@typescript-eslint/no-floating-promises": [ 185 | "error" 186 | ], 187 | "no-return-await": [ 188 | "off" 189 | ], 190 | "@typescript-eslint/return-await": [ 191 | "error" 192 | ], 193 | "no-trailing-spaces": [ 194 | "error" 195 | ], 196 | "dot-notation": [ 197 | "error" 198 | ], 199 | "no-bitwise": [ 200 | "error" 201 | ], 202 | "@typescript-eslint/member-ordering": [ 203 | "error", 204 | { 205 | "default": [ 206 | "public-static-field", 207 | "public-static-method", 208 | "protected-static-field", 209 | "protected-static-method", 210 | "private-static-field", 211 | "private-static-method", 212 | "field", 213 | "constructor", 214 | "method" 215 | ] 216 | } 217 | ] 218 | }, 219 | "overrides": [ 220 | { 221 | "files": [ 222 | ".projenrc.js" 223 | ], 224 | "rules": { 225 | "@typescript-eslint/no-require-imports": "off", 226 | "import/no-extraneous-dependencies": "off" 227 | } 228 | } 229 | ] 230 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | # Logs 3 | logs 4 | *.log 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* 8 | lerna-debug.log* 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | *.lcov 21 | # nyc test coverage 22 | .nyc_output 23 | # Compiled binary addons (https://nodejs.org/api/addons.html) 24 | build/Release 25 | # Dependency directories 26 | node_modules/ 27 | jspm_packages/ 28 | # TypeScript cache 29 | *.tsbuildinfo 30 | # Optional eslint cache 31 | .eslintcache 32 | # Output of 'npm pack' 33 | *.tgz 34 | # Yarn Integrity file 35 | .yarn-integrity 36 | # parcel-bundler cache (https://parceljs.org/) 37 | .cache 38 | appsync/ 39 | # jest-junit artifacts 40 | /test-reports/ 41 | junit.xml 42 | /coverage 43 | /lib 44 | /dist 45 | cdk.out/ 46 | .cdk.staging/ 47 | .parcel-cache/ 48 | !/.projen/tasks.json 49 | !/package.json 50 | !/.npmignore 51 | !/LICENSE 52 | !/.projenrc.js 53 | !version.json 54 | !/.versionrc.json 55 | !/test 56 | !/tsconfig.json 57 | !/src 58 | !/tsconfig.jest.json 59 | !/.eslintrc.json 60 | !/cdk.json -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | /.projenrc.js 3 | /.versionrc.json 4 | /coverage 5 | /test 6 | /tsconfig.json 7 | /src 8 | dist 9 | /tsconfig.json 10 | /.github 11 | /.vscode 12 | /.idea 13 | /.projenrc.js 14 | /tsconfig.jest.json 15 | /.eslintrc.json 16 | cdk.out/ 17 | .cdk.staging/ 18 | !/lib 19 | !/lib/**/*.js 20 | !/lib/**/*.d.ts -------------------------------------------------------------------------------- /.projen/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": { 3 | "compile": { 4 | "name": "compile", 5 | "category": "00.build", 6 | "description": "Only compile" 7 | }, 8 | "test": { 9 | "name": "test", 10 | "category": "10.test", 11 | "description": "Run tests", 12 | "steps": [ 13 | { 14 | "exec": "rm -fr lib/" 15 | }, 16 | { 17 | "exec": "jest --passWithNoTests --all" 18 | }, 19 | { 20 | "spawn": "eslint" 21 | } 22 | ] 23 | }, 24 | "build": { 25 | "name": "build", 26 | "category": "00.build", 27 | "description": "Full release build (test+compile)", 28 | "steps": [ 29 | { 30 | "spawn": "test" 31 | }, 32 | { 33 | "spawn": "compile" 34 | }, 35 | { 36 | "spawn": "synth" 37 | } 38 | ] 39 | }, 40 | "bump": { 41 | "name": "bump", 42 | "category": "20.release", 43 | "description": "Commits a bump to the package version based on conventional commits", 44 | "steps": [ 45 | { 46 | "exec": "standard-version" 47 | } 48 | ], 49 | "condition": "! git log --oneline -1 | grep -q \"chore(release):\"" 50 | }, 51 | "release": { 52 | "name": "release", 53 | "category": "20.release", 54 | "description": "Bumps version & push to master", 55 | "steps": [ 56 | { 57 | "spawn": "bump" 58 | }, 59 | { 60 | "exec": "git push --follow-tags origin master" 61 | } 62 | ], 63 | "condition": "! git log --oneline -1 | grep -q \"chore(release):\"" 64 | }, 65 | "test:watch": { 66 | "name": "test:watch", 67 | "category": "10.test", 68 | "description": "Run jest in watch mode", 69 | "steps": [ 70 | { 71 | "exec": "jest --watch" 72 | } 73 | ] 74 | }, 75 | "test:update": { 76 | "name": "test:update", 77 | "category": "10.test", 78 | "description": "Update jest snapshots", 79 | "steps": [ 80 | { 81 | "exec": "jest --updateSnapshot" 82 | } 83 | ] 84 | }, 85 | "projen:upgrade": { 86 | "name": "projen:upgrade", 87 | "category": "30.maintain", 88 | "description": "upgrades projen to the latest version", 89 | "steps": [ 90 | { 91 | "exec": "yarn upgrade -L projen" 92 | }, 93 | { 94 | "exec": "CI=\"\" yarn projen" 95 | } 96 | ] 97 | }, 98 | "watch": { 99 | "name": "watch", 100 | "category": "00.build", 101 | "description": "Watch & compile in the background", 102 | "steps": [ 103 | { 104 | "exec": "tsc -w" 105 | } 106 | ] 107 | }, 108 | "eslint": { 109 | "name": "eslint", 110 | "category": "10.test", 111 | "description": "Runs eslint against the codebase", 112 | "steps": [ 113 | { 114 | "exec": "eslint --ext .ts,.tsx --fix --no-error-on-unmatched-pattern src test .projenrc.js" 115 | } 116 | ] 117 | }, 118 | "synth": { 119 | "name": "synth", 120 | "category": "00.build", 121 | "description": "Synthesizes your cdk app into cdk.out (part of \"yarn build\")", 122 | "steps": [ 123 | { 124 | "exec": "cdk synth" 125 | } 126 | ] 127 | }, 128 | "deploy": { 129 | "name": "deploy", 130 | "category": "20.release", 131 | "description": "Deploys your CDK app to the AWS cloud", 132 | "steps": [ 133 | { 134 | "exec": "cdk deploy" 135 | } 136 | ] 137 | }, 138 | "destroy": { 139 | "name": "destroy", 140 | "category": "20.release", 141 | "description": "Destroys your cdk app in the AWS cloud", 142 | "steps": [ 143 | { 144 | "exec": "cdk destroy" 145 | } 146 | ] 147 | }, 148 | "diff": { 149 | "name": "diff", 150 | "category": "99.misc", 151 | "description": "Diffs the currently deployed app against your code", 152 | "steps": [ 153 | { 154 | "exec": "cdk diff" 155 | } 156 | ] 157 | } 158 | }, 159 | "env": { 160 | "PATH": "$(npx -c 'echo $PATH')" 161 | }, 162 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 163 | } -------------------------------------------------------------------------------- /.projenrc.js: -------------------------------------------------------------------------------- 1 | const { AwsCdkTypeScriptApp, web, NodePackageManager } = require('projen'); 2 | 3 | const cdkProject = new AwsCdkTypeScriptApp({ 4 | name: 'cdk-appsync-react-demo', 5 | packageManager: NodePackageManager.NPM, 6 | 7 | cdkVersion: '1.79.0', 8 | cdkDependencies: [ 9 | '@aws-cdk/aws-appsync', 10 | '@aws-cdk/aws-cognito', 11 | '@aws-cdk/aws-iam', 12 | '@aws-cdk/core', 13 | ], 14 | deps: [ 15 | 'cdk-appsync-transformer', 16 | ], 17 | 18 | gitignore: [ 19 | 'appsync/', 20 | ], 21 | 22 | // Disable GitHub 23 | mergify: false, 24 | buildWorkflow: false, 25 | releaseWorkflow: false, 26 | rebuildBot: false, 27 | dependabot: false, 28 | pullRequestTemplate: false, 29 | }); 30 | 31 | cdkProject.synth(); 32 | 33 | const reactProject = new web.ReactTypeScriptProject({ 34 | name: 'cdk-appsync-react-demo-frontend', 35 | parent: cdkProject, 36 | outdir: 'frontend', 37 | 38 | deps: [ 39 | '@aws-amplify/auth', 40 | '@aws-amplify/ui-components', 41 | '@aws-amplify/ui-react', 42 | 'aws-amplify', 43 | 'react-query@^2', // I have an open PR for react-query v3 support 44 | 'react-router', 45 | 'react-router-dom', 46 | ], 47 | devDeps: [ 48 | '@graphql-codegen/cli', 49 | '@graphql-codegen/typescript', 50 | '@graphql-codegen/typescript-operations', 51 | '@graphql-codegen/typescript-react-query@alpha', 52 | 'amplify-graphql-docs-generator', 53 | 'aws-sdk@^2', 54 | 'graphql', 55 | ], 56 | 57 | gitignore: [ 58 | 'aws-exports.js', 59 | ], 60 | 61 | tsconfig: { 62 | compilerOptions: { 63 | allowJs: true, 64 | skipLibCheck: true, 65 | esModuleInterop: true, 66 | allowSyntheticDefaultImports: true, 67 | forceConsistentCasingInFileNames: false, 68 | module: 'esnext', 69 | moduleResolution: 'node', 70 | isolatedModules: true, 71 | noEmit: true, 72 | jsx: 'react-jsx', 73 | }, 74 | }, 75 | 76 | // Disable GitHub 77 | mergify: false, 78 | buildWorkflow: false, 79 | releaseWorkflow: false, 80 | rebuildBot: false, 81 | dependabot: false, 82 | pullRequestTemplate: false, 83 | }); 84 | 85 | reactProject.addTask('dev', { 86 | description: 'Runs the application locally', 87 | exec: 'react-scripts start', 88 | }); 89 | 90 | reactProject.addTask('generate-exports', { 91 | description: 'Generates aws-exports.js', 92 | exec: 'node bin/generateExports.js', 93 | }); 94 | 95 | reactProject.addTask('copy-schema', { 96 | exec: 'cp ../appsync/schema.graphql ./schema.graphql', 97 | }); 98 | 99 | reactProject.addTask('generate-statements', { 100 | exec: 'node bin/generateStatements.js', 101 | }); 102 | 103 | reactProject.addTask('codegen', { 104 | description: 'Copies the backend schema and generates frontend code', 105 | exec: 'yarn run copy-schema && yarn run generate-statements && graphql-codegen --config codegen.yml && rm schema.graphql', 106 | }); 107 | 108 | reactProject.synth(); -------------------------------------------------------------------------------- /.versionrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "packageFiles": [ 3 | { 4 | "filename": "version.json", 5 | "type": "json" 6 | } 7 | ], 8 | "bumpFiles": [ 9 | { 10 | "filename": "version.json", 11 | "type": "json" 12 | } 13 | ], 14 | "commitAll": true, 15 | "scripts": { 16 | "postbump": "npx projen && git add ." 17 | } 18 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CDK Appsync Transformer React Demo 2 | 3 | *All commands assume you have proper aws credentials* 4 | 5 | A simple CDK & React example to deploy an AppSync API with Cognito as auth. Uses [AWS Amplify schema directives](https://docs.amplify.aws/cli/graphql-transformer/directives) to transform the graphql schema. 6 | 7 | * Checkout the [blog post](https://kennethwinner.com/2020/12/22/react-query-appsync/) 8 | * Watch the [demo/walkthrough](https://youtu.be/JOYsv_KyNBk) 9 | 10 | ## What's in the box 11 | 12 | ### AWS Resources 13 | * Cognito User Pool 14 | * Cognito Identity Pool 15 | * AppSync API 16 | * AppSync Resolvers 17 | * AppSync Datasources 18 | * DynamoDB Table 19 | * IAM Roles 20 | 21 | ### Schema 22 | 23 | * Posts - uses @model and @auth directives to declare a simple dynamodb backed type 24 | * Todos - uses @http directive to grab todos from https://jsonplaceholder.typicode.com/ 25 | 26 | ## To deploy as is 27 | 28 | 1. Clone The Repository 29 | ```bash 30 | git clone https://github.com/kcwinner/cdk-appsync-react-demo.git 31 | cd cdk-appsync-react-demo 32 | ``` 33 | 34 | 1. Initialize The Project 35 | ```bash 36 | npx projen 37 | ``` 38 | 39 | 1. Test And Deploy 40 | ```bash 41 | npm run test 42 | npm run deploy 43 | ``` 44 | 45 | 1. Generate Exports && GraphQL Types 46 | ``` 47 | cd frontend 48 | yarn run generate-exports 49 | yarn run codegen 50 | ``` 51 | 52 | 1. Run the frontend locally 53 | ```bash 54 | yarn run dev 55 | ``` 56 | 57 | ## References 58 | 59 | * [cdk-appsync-transformer](https://github.com/kcwinner/cdk-appsync-transformer) 60 | * [graphql-code-generator](https://graphql-code-generator.com/) 61 | * [react-query](https://github.com/tannerlinsley/react-query) 62 | * [projen](https://github.com/projen/projen) 63 | * [blog post](https://kennethwinner.com/2020/12/22/react-query-appsync/) 64 | * [video](https://youtu.be/JOYsv_KyNBk) -------------------------------------------------------------------------------- /cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "npx ts-node --prefer-ts-exts src/main.ts" 3 | } -------------------------------------------------------------------------------- /frontend/.env: -------------------------------------------------------------------------------- 1 | SKIP_PREFLIGHT_CHECK=true -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | # Logs 3 | logs 4 | *.log 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* 8 | lerna-debug.log* 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | *.lcov 21 | # nyc test coverage 22 | .nyc_output 23 | # Compiled binary addons (https://nodejs.org/api/addons.html) 24 | build/Release 25 | # Dependency directories 26 | node_modules/ 27 | jspm_packages/ 28 | # TypeScript cache 29 | *.tsbuildinfo 30 | # Optional eslint cache 31 | .eslintcache 32 | # Output of 'npm pack' 33 | *.tgz 34 | # Yarn Integrity file 35 | .yarn-integrity 36 | # parcel-bundler cache (https://parceljs.org/) 37 | .cache 38 | aws-exports.js 39 | /lib 40 | /dist 41 | # Build 42 | /build 43 | !/.projen/tasks.json 44 | !/package.json 45 | !/.npmignore 46 | !/LICENSE 47 | !/.projenrc.js 48 | !version.json 49 | !/.versionrc.json 50 | !/tsconfig.json 51 | !/src 52 | !/react-app-env.d.ts -------------------------------------------------------------------------------- /frontend/.npmignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | /.projenrc.js 3 | /.versionrc.json 4 | /tsconfig.json 5 | /src 6 | dist 7 | /tsconfig.json 8 | /.github 9 | /.vscode 10 | /.idea 11 | /.projenrc.js 12 | # Build 13 | /build 14 | !/lib 15 | !/lib/**/*.js 16 | !/lib/**/*.d.ts -------------------------------------------------------------------------------- /frontend/.projen/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": { 3 | "compile": { 4 | "name": "compile", 5 | "category": "00.build", 6 | "description": "Only compile" 7 | }, 8 | "test": { 9 | "name": "test", 10 | "category": "10.test", 11 | "description": "Runs tests", 12 | "steps": [ 13 | { 14 | "exec": "react-scripts test" 15 | } 16 | ] 17 | }, 18 | "build": { 19 | "name": "build", 20 | "category": "00.build", 21 | "description": "Creates an optimized production build of your React application", 22 | "steps": [ 23 | { 24 | "exec": "react-scripts build" 25 | } 26 | ] 27 | }, 28 | "bump": { 29 | "name": "bump", 30 | "category": "20.release", 31 | "description": "Commits a bump to the package version based on conventional commits", 32 | "steps": [ 33 | { 34 | "exec": "standard-version" 35 | } 36 | ], 37 | "condition": "! git log --oneline -1 | grep -q \"chore(release):\"" 38 | }, 39 | "release": { 40 | "name": "release", 41 | "category": "20.release", 42 | "description": "Bumps version & push to master", 43 | "steps": [ 44 | { 45 | "spawn": "bump" 46 | }, 47 | { 48 | "exec": "git push --follow-tags origin master" 49 | } 50 | ], 51 | "condition": "! git log --oneline -1 | grep -q \"chore(release):\"" 52 | }, 53 | "projen:upgrade": { 54 | "name": "projen:upgrade", 55 | "category": "30.maintain", 56 | "description": "upgrades projen to the latest version", 57 | "steps": [ 58 | { 59 | "exec": "yarn upgrade -L projen" 60 | }, 61 | { 62 | "exec": "CI=\"\" yarn projen" 63 | } 64 | ] 65 | }, 66 | "watch": { 67 | "name": "watch", 68 | "category": "00.build", 69 | "description": "Watch & compile in the background", 70 | "steps": [ 71 | { 72 | "exec": "tsc -w" 73 | } 74 | ] 75 | }, 76 | "dev": { 77 | "name": "dev", 78 | "description": "Runs the application locally", 79 | "steps": [ 80 | { 81 | "exec": "react-scripts start" 82 | } 83 | ] 84 | }, 85 | "eject": { 86 | "name": "eject", 87 | "category": "99.misc", 88 | "description": "Ejects your React application from react-scripts", 89 | "steps": [ 90 | { 91 | "exec": "react-scripts eject" 92 | } 93 | ] 94 | }, 95 | "generate-exports": { 96 | "name": "generate-exports", 97 | "description": "Generates aws-exports.js", 98 | "steps": [ 99 | { 100 | "exec": "node bin/generateExports.js" 101 | } 102 | ] 103 | }, 104 | "copy-schema": { 105 | "name": "copy-schema", 106 | "steps": [ 107 | { 108 | "exec": "cp ../appsync/schema.graphql ./schema.graphql" 109 | } 110 | ] 111 | }, 112 | "generate-statements": { 113 | "name": "generate-statements", 114 | "steps": [ 115 | { 116 | "exec": "node bin/generateStatements.js" 117 | } 118 | ] 119 | }, 120 | "codegen": { 121 | "name": "codegen", 122 | "description": "Copies the backend schema and generates frontend code", 123 | "steps": [ 124 | { 125 | "exec": "yarn run copy-schema && yarn run generate-statements && graphql-codegen --config codegen.yml && rm schema.graphql" 126 | } 127 | ] 128 | } 129 | }, 130 | "env": { 131 | "PATH": "$(npx -c 'echo $PATH')" 132 | }, 133 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 134 | } -------------------------------------------------------------------------------- /frontend/.versionrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "packageFiles": [ 3 | { 4 | "filename": "version.json", 5 | "type": "json" 6 | } 7 | ], 8 | "bumpFiles": [ 9 | { 10 | "filename": "version.json", 11 | "type": "json" 12 | } 13 | ], 14 | "commitAll": true, 15 | "scripts": { 16 | "postbump": "npx projen && git add ." 17 | } 18 | } -------------------------------------------------------------------------------- /frontend/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # my project -------------------------------------------------------------------------------- /frontend/amplifyBase.graphql: -------------------------------------------------------------------------------- 1 | scalar AWSDate 2 | scalar AWSTime 3 | scalar AWSDateTime 4 | scalar AWSTimestamp 5 | scalar AWSEmail 6 | scalar AWSJSON 7 | scalar AWSURL 8 | scalar AWSPhone 9 | scalar AWSIPAddress 10 | scalar BigInt 11 | scalar Double 12 | 13 | directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION 14 | 15 | # Allows transformer libraries to deprecate directive arguments. 16 | directive @deprecated(reason: String) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ENUM | ENUM_VALUE 17 | 18 | directive @aws_auth(cognito_groups: [String!]!) on FIELD_DEFINITION 19 | directive @aws_api_key on FIELD_DEFINITION | OBJECT 20 | directive @aws_iam on FIELD_DEFINITION | OBJECT 21 | directive @aws_oidc on FIELD_DEFINITION | OBJECT 22 | directive @aws_cognito_user_pools(cognito_groups: [String!]) on FIELD_DEFINITION | OBJECT -------------------------------------------------------------------------------- /frontend/bin/generateExports.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | const AWS = require('aws-sdk'); 6 | const cloudformation = new AWS.CloudFormation(); 7 | 8 | const REGION = process.env.REGION || 'us-east-2' 9 | 10 | const STACK_NAME = `cdk-appsync-react-demo`; 11 | 12 | const appsyncGraphQLURLOutputKey = 'appsyncGraphQLEndpointOutput'; 13 | const userPoolIdOutputKey = 'awsUserPoolId'; 14 | const userPoolClientOutputKey = 'awsUserPoolWebClientId'; 15 | const identityPoolOutputKey = 'awsIdentityPoolId'; 16 | const authenticationTypeOutputKey = 'awsAppsyncAuthenticationType'; 17 | 18 | let awsmobile = { 19 | aws_project_region: REGION, 20 | aws_appsync_graphqlEndpoint: '', 21 | aws_appsync_region: REGION, 22 | aws_appsync_authenticationType: 'AWS_IAM', 23 | aws_cognito_region: REGION, 24 | aws_user_pools_id: '', 25 | aws_user_pools_web_client_id: '', 26 | aws_cognito_identity_pool_id: '' 27 | }; 28 | 29 | main(); 30 | 31 | async function main() { 32 | const exportFileName = 'aws-exports.js'; 33 | console.log('Generating aws-exports.js') 34 | 35 | var describeStackParams = { 36 | StackName: STACK_NAME 37 | }; 38 | const stackResponse = await cloudformation.describeStacks(describeStackParams).promise() 39 | const stack = stackResponse.Stacks[0]; 40 | 41 | const appsyncGraphQLEndpoint = stack.Outputs.find(output => { 42 | return output.OutputKey === appsyncGraphQLURLOutputKey; 43 | }) 44 | 45 | const userPoolId = stack.Outputs.find(output => { 46 | return output.OutputKey === userPoolIdOutputKey; 47 | }) 48 | 49 | const userPoolWebClientId = stack.Outputs.find(output => { 50 | return output.OutputKey === userPoolClientOutputKey; 51 | }) 52 | 53 | const identityPoolId = stack.Outputs.find(output => { 54 | return output.OutputKey === identityPoolOutputKey; 55 | }) 56 | 57 | const authenticationType = stack.Outputs.find(output => { 58 | return output.OutputKey === authenticationTypeOutputKey; 59 | }) 60 | 61 | awsmobile.aws_appsync_graphqlEndpoint = appsyncGraphQLEndpoint.OutputValue; 62 | awsmobile.aws_appsync_authenticationType = authenticationType.OutputValue; 63 | awsmobile.aws_user_pools_id = userPoolId.OutputValue; 64 | awsmobile.aws_user_pools_web_client_id = userPoolWebClientId.OutputValue; 65 | awsmobile.aws_cognito_identity_pool_id = identityPoolId.OutputValue; 66 | 67 | let awsExportsPath = path.join(__dirname, '..', 'src', exportFileName); 68 | 69 | let data = `const awsmobile = ${JSON.stringify(awsmobile, null, 4)} 70 | 71 | export default awsmobile;`.replace(/^ export default awsmobile/gm, 'export default awsmobile'); 72 | 73 | fs.writeFileSync(awsExportsPath, data); 74 | console.log(`Wrote exports to ${awsExportsPath}`); 75 | } -------------------------------------------------------------------------------- /frontend/bin/generateStatements.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs-extra'); 3 | const { generate } = require('amplify-graphql-docs-generator'); 4 | 5 | generateStatements(); 6 | 7 | async function generateStatements() { 8 | const outputPath = path.join(__dirname, '..', './src/graphql/'); 9 | 10 | const schemaPath = path.join(__dirname, '..', 'schema.graphql'); 11 | const language = 'typescript'; 12 | 13 | try { 14 | fs.ensureDirSync(outputPath); 15 | generate(schemaPath, outputPath, { 16 | separateFiles: true, 17 | language, 18 | maxDepth: 5 19 | }); 20 | } catch(err) { 21 | console.error(err) 22 | } 23 | } -------------------------------------------------------------------------------- /frontend/codegen.yml: -------------------------------------------------------------------------------- 1 | overwrite: true 2 | schema: "./*.graphql" 3 | documents: "src/graphql/*.ts" 4 | generates: 5 | src/lib/api.ts: 6 | plugins: 7 | - "typescript" 8 | - "typescript-operations" 9 | - "typescript-react-query" 10 | config: 11 | maybeValue: 'T | null | undefined' 12 | fetcher: '../lib/fetcher#amplifyFetcher' 13 | hooks: 14 | afterAllFileWrite: 15 | - prettier --write -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cdk-appsync-react-demo-frontend", 3 | "bin": {}, 4 | "scripts": { 5 | "projen": "npx projen", 6 | "start": "npx projen start", 7 | "compile": "npx projen compile", 8 | "test": "npx projen test", 9 | "build": "npx projen build", 10 | "bump": "npx projen bump", 11 | "release": "npx projen release", 12 | "projen:upgrade": "npx projen projen:upgrade", 13 | "watch": "npx projen watch", 14 | "dev": "npx projen dev", 15 | "eject": "npx projen eject", 16 | "generate-exports": "npx projen generate-exports", 17 | "copy-schema": "npx projen copy-schema", 18 | "generate-statements": "npx projen generate-statements", 19 | "codegen": "npx projen codegen" 20 | }, 21 | "devDependencies": { 22 | "@graphql-codegen/cli": "^1.19.4", 23 | "@graphql-codegen/typescript": "^1.19.0", 24 | "@graphql-codegen/typescript-operations": "^1.17.12", 25 | "@graphql-codegen/typescript-react-query": "alpha", 26 | "@testing-library/jest-dom": "^5.11.6", 27 | "@testing-library/react": "^11.2.2", 28 | "@testing-library/user-event": "^12.6.0", 29 | "@types/jest": "^26.0.19", 30 | "@types/node": "^14.14.14", 31 | "@types/react": "^17.0.0", 32 | "@types/react-dom": "^17.0.0", 33 | "amplify-graphql-docs-generator": "^2.2.1", 34 | "aws-sdk": "^2", 35 | "graphql": "^15.4.0", 36 | "projen": "^0.6.13", 37 | "standard-version": "^9.0.0", 38 | "typescript": "^4.0.3" 39 | }, 40 | "peerDependencies": {}, 41 | "dependencies": { 42 | "@aws-amplify/auth": "^3.4.16", 43 | "@aws-amplify/ui-components": "^0.9.8", 44 | "@aws-amplify/ui-react": "^0.2.33", 45 | "aws-amplify": "^3.3.13", 46 | "react": "^17.0.1", 47 | "react-dom": "^17.0.1", 48 | "react-query": "^2", 49 | "react-router": "^5.2.0", 50 | "react-router-dom": "^5.2.0", 51 | "react-scripts": "^4.0.0", 52 | "web-vitals": "^1.0.1" 53 | }, 54 | "bundledDependencies": [], 55 | "keywords": [], 56 | "license": "Apache-2.0", 57 | "version": "0.0.0", 58 | "eslintConfig": { 59 | "extends": [ 60 | "react-app", 61 | "react-app/jest" 62 | ] 63 | }, 64 | "browserslist": { 65 | "production": [ 66 | ">0.2%", 67 | "not dead", 68 | "not op_mini all" 69 | ], 70 | "development": [ 71 | "last 1 chrome version", 72 | "last 1 firefox version", 73 | "last 1 safari version" 74 | ] 75 | }, 76 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 77 | } -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 24 | React App 25 | 26 | 27 | 28 |
29 | 38 | 39 | -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [], 5 | "start_url": ".", 6 | "display": "standalone", 7 | "theme_color": "#000000", 8 | "background_color": "#ffffff" 9 | } -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: -------------------------------------------------------------------------------- /frontend/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-header { 6 | background-color: #282c34; 7 | min-height: 100vh; 8 | display: flex; 9 | flex-direction: column; 10 | align-items: center; 11 | justify-content: center; 12 | font-size: calc(10px + 2vmin); 13 | color: white; 14 | } 15 | 16 | .Navbar { 17 | background: linear-gradient(90deg, rgb(180, 76, 7) 0%, rgb(241, 255, 116) 100%); 18 | height: 80px; 19 | display: flex; 20 | justify-content: center; 21 | align-items: center; 22 | font-size: 1.2rem; 23 | } 24 | 25 | .navbar-logo { 26 | color: #fff; 27 | justify-self: start; 28 | margin-left: 20px; 29 | cursor: pointer; 30 | } 31 | 32 | .nav-menu { 33 | display: grid; 34 | grid-template-columns: repeat(5, auto); 35 | grid-gap: 10px; 36 | list-style: none; 37 | text-align: center; 38 | width: 70vw; 39 | justify-content: end; 40 | margin-right: 2rem; 41 | } 42 | 43 | .nav-links { 44 | color: white; 45 | text-decoration: none; 46 | padding: 0.5rem 1rem; 47 | } 48 | 49 | .nav-links:hover { 50 | background-color: #6d76f7; 51 | border-radius: 4px; 52 | transition: all 0.2s ease-out; 53 | } 54 | 55 | .fa-bars { 56 | color: #fff; 57 | } 58 | 59 | .nav-links-mobile { 60 | display: none; 61 | } 62 | 63 | .menu-icon { 64 | display: none; 65 | } 66 | 67 | @media screen and (max-width: 960px) { 68 | .NavbarItems { 69 | position: relative; 70 | } 71 | 72 | .nav-menu { 73 | display: flex; 74 | flex-direction: column; 75 | width: 100%; 76 | height: 500px; 77 | position: absolute; 78 | top: 80px; 79 | left: -100%; 80 | opacity: 1; 81 | transition: all 0.5s ease; 82 | } 83 | 84 | .nav-menu.active { 85 | background: #6668f4; 86 | left: 0; 87 | opacity: 1; 88 | transition: all 0.5s ease; 89 | z-index: 1; 90 | } 91 | 92 | .nav-links { 93 | text-align: center; 94 | padding: 2rem; 95 | width: 100%; 96 | display: table; 97 | } 98 | 99 | .nav-links:hover { 100 | background-color: #7577fa; 101 | border-radius: 0; 102 | } 103 | 104 | .navbar-logo { 105 | position: absolute; 106 | top: 0; 107 | left: 0; 108 | transform: translate(25%, 50%); 109 | } 110 | 111 | .menu-icon { 112 | display: block; 113 | position: absolute; 114 | top: 0; 115 | right: 0; 116 | transform: translate(-100%, 60%); 117 | font-size: 1.8rem; 118 | cursor: pointer; 119 | } 120 | 121 | .fa-times { 122 | color: #fff; 123 | font-size: 2rem; 124 | } 125 | 126 | .nav-links-mobile { 127 | display: block; 128 | text-align: center; 129 | padding: 1.5rem; 130 | margin: 2rem auto; 131 | border-radius: 4px; 132 | width: 80%; 133 | background: #4ad9e4; 134 | text-decoration: none; 135 | color: #fff; 136 | font-size: 1.5rem; 137 | } 138 | 139 | .nav-links-mobile:hover { 140 | background: #fff; 141 | color: #6568F4; 142 | transition: 250ms; 143 | } 144 | 145 | Button { 146 | display: none; 147 | } 148 | } -------------------------------------------------------------------------------- /frontend/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 3 | import './App.css'; 4 | 5 | import { AuthState, onAuthUIStateChange } from '@aws-amplify/ui-components'; 6 | import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'; 7 | 8 | import { API } from './lib/fetcher'; 9 | 10 | import { Posts } from './components/posts'; 11 | import { Todos } from './components/todos'; 12 | 13 | import Amplify from 'aws-amplify'; 14 | import config from './aws-exports'; 15 | 16 | Amplify.configure(config); 17 | 18 | function App() { 19 | 20 | useEffect(() => { 21 | return onAuthUIStateChange((nextAuthState, authData: any) => { 22 | API.updateIsSignedIn(nextAuthState === AuthState.SignedIn); 23 | }); 24 | }, []); 25 | 26 | return ( 27 |
28 | 36 |
37 | 38 | 39 | } /> 40 | } /> 41 | } /> 42 | 43 | 44 |
45 |
46 | ); 47 | } 48 | 49 | export default withAuthenticator(App); 50 | -------------------------------------------------------------------------------- /frontend/src/components/posts.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { Auth } from '@aws-amplify/auth'; 3 | import { useMutation } from 'react-query'; 4 | 5 | import { useListPostsQuery, CreatePostDocument, CreatePostInput, Post } from '../lib/api'; 6 | import { API } from '../lib/fetcher'; 7 | 8 | const initialState = { title: '', content: '', username: '' }; 9 | 10 | export function Posts() { 11 | const [post, setPost] = useState(initialState); 12 | const { title, content } = post; 13 | 14 | const { data, isLoading, refetch } = useListPostsQuery(null, { 15 | refetchOnWindowFocus: false 16 | }); 17 | 18 | // useCreatePostMutation isn't working correctly right now 19 | const [createPost] = useMutation(async (input: CreatePostInput) => { 20 | const result = await API.getInstance().query(CreatePostDocument, { input }); 21 | return result.data?.createPost as Post; 22 | }); 23 | 24 | const onChange = (e) => { 25 | setPost(() => ({ ...post, [e.target.name]: e.target.value })) 26 | } 27 | 28 | const createNewPost = async () => { 29 | if (!title || !content) return 30 | 31 | const userData = await Auth.currentAuthenticatedUser(); 32 | 33 | const input = { 34 | ...post, 35 | username: userData.username 36 | }; 37 | 38 | const createResult = await createPost(input); 39 | if (createResult) { 40 | refetch(); 41 | } 42 | } 43 | 44 | if (isLoading) return
Loading...
; 45 | 46 | return ( 47 |
48 |
49 |

Posts:

50 | { 51 | data?.listPosts?.items 52 | ? data?.listPosts?.items?.map(post => { 53 | return ( 54 |
55 |

Title: {post.title}

56 |
Owner: {post.owner}
57 |
Content: {post.content}
58 |
59 | ) 60 | }) 61 | :

No posts found

62 | } 63 |
64 |
65 |
66 |
67 |

Create Post:

68 |
69 | 70 |
71 |
72 |