└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Building your first Fullstack Serverless App with AWS Amplify 2 | 3 | In this workshop we'll learn how to build cloud-enabled web applications with Angular & [AWS Amplify](https://aws-amplify.github.io/). 4 | 5 | ![](https://i.imgur.com/GW1Nk5B.png) 6 | 7 | ### Topics we'll be covering: 8 | 9 | - [Authentication](https://github.com/gsans/aws-amplify-workshop-angular#adding-authentication) 10 | - [GraphQL API with AWS AppSync](https://github.com/gsans/aws-amplify-workshop-angular#adding-a-graphql-api) 11 | - [Hosting](https://github.com/gsans/aws-amplify-workshop-angular#hosting) 12 | - [Multiple Environments](https://github.com/gsans/aws-amplify-workshop-react#working-with-multiple-environments) 13 | - [Deploying via the Amplify Console](https://github.com/gsans/aws-amplify-workshop-angular#amplify-console) 14 | - [Removing / Deleting Services](https://github.com/gsans/aws-amplify-workshop-angular#removing-services) 15 | 16 | 23 | 24 | ## Redeeming your AWS Credit 25 | 26 | 1. Visit the [AWS Console](https://console.aws.amazon.com/console). 27 | 2. In the top right corner, under your username, click on __My Account__. 28 | 29 | 3. In the left menu under Home, click __Credits__. 30 | 31 | 32 | ## Pre-requisites 33 | 34 | - Node: `11.13.0`. Visit [Node](https://nodejs.org/en/download/) 35 | - npm: `6.9.0`. Packaged with Node otherwise run upgrade 36 | 37 | ```bash 38 | npm install -g npm 39 | ``` 40 | 41 | ## Getting Started - Creating the Application 42 | 43 | To get started, we first need to create a new Angular project & change into the new directory using the [Angular CLI](https://cli.angular.io/). 44 | 45 | If you already have it installed, skip to the next step. If not, either install the CLI & create the app or create a new app using: 46 | 47 | ```bash 48 | npm install -g @angular/cli 49 | ng new amplify-app 50 | ``` 51 | 52 | Now change into the new app directory and make sure it runs 53 | 54 | ```bash 55 | cd amplify-app 56 | npm install 57 | ng serve 58 | ``` 59 | ## Changes to Angular CLI project 60 | 61 | Add type definitions for __Node__ by changing `src/tsconfig.app.json`. This is a requirement from `aws-js-sdk`. 62 | 63 | ```json 64 | { 65 | "compilerOptions": { 66 | "types": ["node"] 67 | }, 68 | } 69 | ``` 70 | 71 | Add the following code, to the top of `src/polyfills.ts`. This is a requirement for Angular 6+. 72 | 73 | ```js 74 | declare global { 75 | interface Window { global: any; } 76 | } 77 | window.global = window; 78 | ``` 79 | 80 | ## Installing the CLI & Initializing a new AWS Amplify Project 81 | 82 | Let's now install the AWS Amplify & AWS Amplify Angular libraries: 83 | 84 | ```bash 85 | npm install --save aws-amplify aws-amplify-angular 86 | ``` 87 | 88 | ### Installing the AWS Amplify CLI 89 | 90 | Next, we'll install the AWS Amplify CLI: 91 | 92 | ```bash 93 | npm install -g @aws-amplify/cli 94 | ``` 95 | 96 | Now we need to configure the CLI with our credentials: 97 | 98 | ```js 99 | amplify configure 100 | ``` 101 | 102 | > If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U). 103 | 104 | Here we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue: 105 | - Specify the AWS Region: __ap-south-1(Mumbai)__ 106 | - Specify the username of the new IAM user: __amplify-app__ 107 | > In the AWS Console, click __Next: Permissions__, __Next: Tags__, __Next: Review__, & __Create User__ to create the new IAM user. Then, return to the command line & press Enter. 108 | - Enter the access key of the newly created user: 109 | accessKeyId: __()__ 110 | secretAccessKey: __()__ 111 | - Profile Name: __default__ 112 | 113 | > To view the new created IAM User go to the dashboard at [https://console.aws.amazon.com/iam/home#/users/](https://console.aws.amazon.com/iam/home#/users/). Also be sure that your region matches your selection. 114 | 115 | ### Initializing A New Project 116 | 117 | ```bash 118 | amplify init 119 | ``` 120 | 121 | - Enter a name for the project: __amplify-app__ 122 | - Enter a name for the environment: __dev__ 123 | - Choose your default editor: __Visual Studio Code__ 124 | - Please choose the type of app that you're building __javascript__ 125 | - What javascript framework are you using __angular__ 126 | - Source Directory Path: __src__ 127 | - Distribution Directory Path: __dist/amplify-app__ 128 | - Build Command: __npm run-script build__ 129 | - Start Command: __ng serve__ 130 | - Please choose the profile you want to use: __default__ 131 | - Do you want to use an AWS profile? __Yes__ 132 | - Please choose the profile you want to use __default__ 133 | 134 | Now, the AWS Amplify CLI has iniatilized a new project & you will see a new folder: __amplify__. The files in this folder hold your project configuration. 135 | 136 | ```bash 137 | 138 | |_ amplify 139 | |_ .config 140 | |_ #current-cloud-backend 141 | |_ backend 142 | team-provider-info.json 143 | ``` 144 | 145 | ## Adding Authentication 146 | 147 | To add authentication, we can use the following command: 148 | 149 | ```sh 150 | amplify add auth 151 | ``` 152 | 153 | > When prompted choose 154 | - Do you want to use default authentication and security configuration?: __Default configuration__ 155 | - How do you want users to be able to sign in when using your Cognito User Pool?: __Username__ 156 | - What attributes are required for signing up? (Press to select, to toggle all, to 157 | invert selection): __Email__ 158 | 159 | Now, we'll run the push command and the cloud resources will be created in our AWS account. 160 | 161 | ```bash 162 | amplify push 163 | ``` 164 | 165 | To quickly check your newly created __Cognito User Pool__ you can run 166 | 167 | ```bash 168 | amplify status 169 | ``` 170 | 171 | > To access the __AWS Cognito Console__ at any time, go to the dashboard at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/). Also be sure that your region is set correctly. 172 | 173 | ### Configuring the Angular Application 174 | 175 | Now, our resources are created & we can start using them! 176 | 177 | The first thing we need to do is to configure our Angular application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated `aws-exports.js` file that is now in our `src` folder. 178 | 179 | To configure the app, open __main.ts__ and add the following code below the last import: 180 | 181 | ```js 182 | import Amplify from 'aws-amplify'; 183 | import amplify from './aws-exports'; 184 | Amplify.configure(amplify); 185 | ``` 186 | 187 | Now, our app is ready to start using our AWS services. 188 | 189 | ### Importing the Angular Module 190 | 191 | Add the Amplify Module and Service to `src/app/app.module.ts`: 192 | 193 | ```js 194 | import { AmplifyAngularModule, AmplifyService } from 'aws-amplify-angular'; 195 | 196 | @NgModule({ 197 | imports: [ 198 | AmplifyAngularModule 199 | ], 200 | providers: [ 201 | AmplifyService 202 | ] 203 | }); 204 | ``` 205 | 206 | ### Using Amplify Service 207 | 208 | The `AmplifyService` provides access to AWS Amplify core categories via Dependency Injection: auth, analytics, storage, api, cache, pubsub; and authentication state via Observables. 209 | 210 | ### Using the Authenticator Component 211 | 212 | AWS Amplify provides UI components that you can use in your App. Let's add these components to the project 213 | 214 | ```bash 215 | npm i --save @aws-amplify/ui 216 | ``` 217 | 218 | Also include these imports to the top of `styles.css` 219 | 220 | ```css 221 | @import "~@aws-amplify/ui/src/Theme.css"; 222 | @import "~@aws-amplify/ui/src/Angular.css"; 223 | ``` 224 | 225 | In order to use the Authenticator Component add it to __src/app.component.html__: 226 | 227 | ```html 228 | 229 | ``` 230 | 231 | Now, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up & sign in. 232 | 233 | > To view any users that were created, go back to the __Cognito__ dashboard at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/). Also be sure that your region is set correctly. 234 | 235 | Alternatively we can also use 236 | 237 | ```bash 238 | amplify console auth 239 | ``` 240 | 241 | ### Accessing User Data 242 | 243 | We can access the user's info now that they are signed in by calling `currentAuthenticatedUser()` which returns a Promise. 244 | 245 | ```js 246 | import { AmplifyService } from 'aws-amplify-angular'; 247 | 248 | @Component(...) 249 | export class AppComponent { 250 | constructor(public amplify: AmplifyService) { 251 | amplify.auth().currentAuthenticatedUser().then(console.log) 252 | } 253 | } 254 | ``` 255 | 256 | ### Custom authentication strategies 257 | 258 | The `Authenticator` Component is a really easy way to get up and running with authentication, but in a real-world application we probably want more control over how our form looks & functions. 259 | 260 | Let's look at how we might create our own authentication flow. 261 | 262 | To get started, we would probably want to create input fields that would hold user input data in the state. For instance when signing up a new user, we would probably need 2 inputs to capture the user's email & password. 263 | 264 | To do this, we could create a form like: 265 | 266 | ```html 267 |
268 |
269 | 270 | 271 |
272 |
273 | 274 | 275 |
276 | 277 |
278 | ``` 279 | 280 | We'd also need to have a method that signed up & signed in users. We can us the Auth class to do this. The Auth class has over 30 methods including things like `signUp`, `signIn`, `confirmSignUp`, `confirmSignIn`, & `forgotPassword`. These functions return a promise so they need to be handled asynchronously. 281 | 282 | ```js 283 | import { Auth } from 'aws-amplify'; 284 | 285 | export class SignupComponent implements OnInit { 286 | public signup: FormGroup; 287 | 288 | constructor( 289 | private fb: FormBuilder, 290 | ) { } 291 | 292 | ngOnInit() { 293 | this.signup = this.fb.group({ 294 | 'email': ['', Validators.required], 295 | 'password': ['', Validators.required] 296 | }); 297 | } 298 | 299 | onSignup(value: any) { 300 | const email = value.email, password = value.password; 301 | Auth.signUp(email, password).then( _ => { 302 | this.success = true; 303 | }).catch(console.log); 304 | } 305 | ``` 306 | 307 | ## Adding a GraphQL API 308 | 309 | To add a GraphQL API, we can use the following command: 310 | 311 | ```sh 312 | amplify add api 313 | ``` 314 | 315 | Answer the following questions 316 | 317 | - Please select from one of the below mentioned services __GraphQL__ 318 | - Provide API name: __RestaurantAPI__ 319 | - Choose an authorization type for the API __API key__ 320 | - Do you have an annotated GraphQL schema? __No__ 321 | - Do you want a guided schema creation? __Yes__ 322 | - What best describes your project: __Single object with fields (e.g., “Todo” with ID, name, description)__ 323 | - Do you want to edit the schema now? __Yes__ 324 | 325 | > When prompted, update the schema to the following: 326 | 327 | ```graphql 328 | type Restaurant @model { 329 | id: ID! 330 | clientId: String 331 | name: String! 332 | description: String! 333 | city: String! 334 | } 335 | ``` 336 | 337 | > Next, let's push the configuration to our account: 338 | 339 | ```bash 340 | amplify push 341 | ``` 342 | 343 | - Are you sure you want to continue? __Yes__ 344 | - Do you want to generate code for your newly created GraphQL API __Yes__ 345 | - Choose the code generation language target __typescript__ 346 | - Enter the file name pattern of graphql queries, mutations and subscriptions __src/graphql/**/*.ts__ 347 | - Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions __Yes__ 348 | - Enter maximum statement depth [increase from default if your schema is deeply nested] __2__ 349 | - Enter the file name for the generated code __src/API.ts__ 350 | 351 | Notice your __GraphQL endpoint__ and __API KEY__. 352 | 353 | This step created a new AWS AppSync API. Use the command below to access the AWS AppSync dashboard. Make sure that your region is correct. 354 | 355 | ```bash 356 | amplify console api 357 | ``` 358 | 359 | - Please select from one of the below mentioned services __GraphQL__ 360 | 361 | 362 | ### Adding mutations from within the AWS AppSync Console 363 | 364 | In the AWS AppSync console, on the left side click on Queries. 365 | 366 | Execute the following mutation to create a new restaurant in the API: 367 | 368 | ```graphql 369 | mutation createRestaurant { 370 | createRestaurant(input: { 371 | name: "Nobu" 372 | description: "Great Sushi" 373 | city: "New York" 374 | }) { 375 | id name description city 376 | } 377 | } 378 | ``` 379 | 380 | Now, let's query for the restaurant: 381 | 382 | ```graphql 383 | query listRestaurants { 384 | listRestaurants { 385 | items { 386 | id 387 | name 388 | description 389 | city 390 | } 391 | } 392 | } 393 | ``` 394 | 395 | We can even add search / filter capabilities when querying: 396 | 397 | ```graphql 398 | query searchRestaurants { 399 | listRestaurants(filter: { 400 | city: { 401 | contains: "New York" 402 | } 403 | }) { 404 | items { 405 | id 406 | name 407 | description 408 | city 409 | } 410 | } 411 | } 412 | ``` 413 | 414 | ### Interacting with the GraphQL API from our client application - Querying for data 415 | 416 | Now that the GraphQL API is created we can begin interacting with it! 417 | 418 | The first thing we'll do is perform a query to fetch data from our API. 419 | 420 | To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI. 421 | 422 | > Read more about the __Amplify GraphQL Client__ [here](https://aws-amplify.github.io/docs/js/api#amplify-graphql-client). 423 | 424 | 425 | ```js 426 | import { API, graphqlOperation } from 'aws-amplify'; 427 | import { listRestaurants } from '../graphql/queries'; 428 | import { Restaurant } from './types/restaurant'; 429 | 430 | @Component({ 431 | template: ` 432 |
433 |
434 | {{ restaurant.name }} 435 |
436 |
` 437 | }) 438 | export class AppComponent implements OnInit { 439 | restaurants: Array; 440 | 441 | async ngOnInit() { 442 | var response = await API.graphql(graphqlOperation(listRestaurants)) 443 | this.restaurants = (response as any).data.listRestaurants.items; 444 | } 445 | } 446 | ``` 447 | 448 | ## Performing mutations 449 | 450 | Now, let's look at how we can create mutations. 451 | 452 | ```js 453 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 454 | import { createRestaurant } from '../../graphql/mutations' 455 | 456 | @Component(...) 457 | export class HomeComponent implements OnInit { 458 | public createForm: FormGroup; 459 | 460 | constructor(private fb: FormBuilder) { } 461 | 462 | async ngOnInit() { 463 | this.createForm = this.fb.group({ 464 | 'name': ['', Validators.required], 465 | 'description': ['', Validators.required], 466 | 'city': ['', Validators.required] 467 | }); 468 | var response = await API.graphql(graphqlOperation(listRestaurants)); 469 | this.restaurants = (response as any).data.listRestaurants.items; 470 | } 471 | 472 | public async onCreate(restaurant: any) { 473 | try { 474 | await API.graphql(graphqlOperation(createRestaurant, { 475 | input: restaurant 476 | })); 477 | console.log('item created!'); 478 | this.restaurants = [restaurant, ...this.restaurants]; 479 | this.createForm.reset(); 480 | } 481 | catch (e) { 482 | console.log('error creating restaurant...', e); 483 | } 484 | } 485 | } 486 | ``` 487 | 488 | ### GraphQL Subscriptions 489 | 490 | Next, let's see how we can create a subscription to subscribe to changes of data in our API. 491 | 492 | To do so, we need to define the subscription, listen for the subscription, & update the state whenever a new piece of data comes in through the subscription. 493 | 494 | ```js 495 | import * as Observable from 'zen-observable'; 496 | import { onCreateRestaurant } from '../../graphql/subscriptions'; 497 | 498 | @Component(...) 499 | export class HomeComponent implements OnInit { 500 | ngOnInit() { 501 | var subscription = API.graphql( 502 | graphqlOperation(onCreateRestaurant) 503 | ) as Observable; 504 | 505 | subscription.subscribe({ 506 | next: (sourceData) => { 507 | const newRestaurant = (sourceData as any).value.data.onCreateRestaurant 508 | this.restaurants = [newRestaurant, ...this.restaurants]; 509 | } 510 | }); 511 | } 512 | } 513 | ``` 514 | 515 | ## Hosting 516 | 517 | To deploy & host your app on AWS, we can use the `hosting` category. 518 | 519 | ```sh 520 | amplify add hosting 521 | ``` 522 | 523 | - Select the environment setup: __DEV (S3 only with HTTP)__ 524 | - hosting bucket name __YOURBUCKETNAME__ 525 | - index doc for the website __index.html__ 526 | - error doc for the website __index.html__ 527 | 528 | Now, everything is set up & we can publish it: 529 | 530 | ```sh 531 | amplify publish 532 | ``` 533 | 534 | ## Working with multiple environments 535 | 536 | You can create multiple environments for your application in which to create & test out new features without affecting the main environment which you are working on. 537 | 538 | When you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created back into the original environment. 539 | 540 | Let's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the pet owner. 541 | 542 | First, we'll initialize a new environment using `amplify init`: 543 | 544 | ```sh 545 | amplify init 546 | ``` 547 | 548 | - Do you want to use an existing environment? __N__ 549 | - Enter a name for the environment: __apiupdate__ 550 | - Do you want to use an AWS profile? __Y__ 551 | - __amplify-workshop-user__ 552 | 553 | Once the new environment is initialized, we should be able to see some information about our environment setup by running: 554 | 555 | ```sh 556 | amplify env list 557 | 558 | | Environments | 559 | | ------------ | 560 | | dev | 561 | | *apiupdate | 562 | ``` 563 | 564 | Now we can update the GraphQL Schema in `amplify/backend/api/RestaurantAPI/schema.graphql` to the following (adding the owner field): 565 | 566 | ```graphql 567 | type Restaurant @model { 568 | ... 569 | owner: String 570 | } 571 | ``` 572 | 573 | Now, we can create this new stack by running `amplify push`: 574 | 575 | ```sh 576 | amplify push 577 | ``` 578 | 579 | After we test it out, we can now merge it into our original dev environment: 580 | 581 | ```sh 582 | amplify env checkout dev 583 | 584 | amplify status 585 | 586 | amplify push 587 | ``` 588 | 589 | - Do you want to update code for your updated GraphQL API? __Y__ 590 | - Do you want to generate GraphQL statements? __Y__ 591 | 592 | 593 | ## Deploying via the Amplify Console 594 | 595 | We have looked at deploying via the Amplify CLI hosting category, but what about if we wanted continous deployment? For this, we can use the [Amplify Console](https://aws.amazon.com/amplify/console/) to deploy the application. 596 | 597 | The first thing we need to do is [create a new GitHub repo](https://github.com/new) for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard & initialize git in our local project: 598 | 599 | ```sh 600 | git init 601 | 602 | git remote add origin git@github.com:username/project-name.git 603 | 604 | git add . 605 | 606 | git commit -m 'initial commit' 607 | 608 | git push origin master 609 | ``` 610 | 611 | Next we'll visit the Amplify Console in our AWS account at [https://ap-south-1.console.aws.amazon.com/amplify/home](https://ap-south-1.console.aws.amazon.com/amplify/home). 612 | 613 | Here, we'll click __Get Started__ to create a new deployment. Next, authorize Github as the repository service. 614 | 615 | Next, we'll choose the new repository & branch for the project we just created & click __Next__. 616 | 617 | In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click __Next__. 618 | 619 | Finally, we can click __Save and Deploy__ to deploy our application! 620 | 621 | Now, we can push updates to Master to update our application. 622 | 623 | 624 | ## Removing Services 625 | 626 | If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the `amplify remove` command: 627 | 628 | ```sh 629 | amplify remove auth 630 | 631 | amplify push 632 | ``` 633 | 634 | If you are unsure of what services you have enabled at any time, you can run the `amplify status` command: 635 | 636 | ```sh 637 | amplify status 638 | ``` 639 | 640 | `amplify status` will give you the list of resources that are currently enabled in your app. --------------------------------------------------------------------------------