{"id":16979991,"url":"https://github.com/gsans/code-chrysalis-workshop","last_synced_at":"2025-03-21T23:13:47.113Z","repository":{"id":78168737,"uuid":"196958245","full_name":"gsans/code-chrysalis-workshop","owner":"gsans","description":"Building Full Stack GraphQL Applications with AWS Amplify and Angular","archived":false,"fork":false,"pushed_at":"2019-07-15T13:08:01.000Z","size":12,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-26T17:32:28.266Z","etag":null,"topics":["angular","awsamplify","awsamplifyclient","awsappsync"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gsans.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-07-15T08:34:33.000Z","updated_at":"2019-07-17T07:52:28.000Z","dependencies_parsed_at":"2023-04-09T14:33:03.114Z","dependency_job_id":null,"html_url":"https://github.com/gsans/code-chrysalis-workshop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcode-chrysalis-workshop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcode-chrysalis-workshop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcode-chrysalis-workshop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcode-chrysalis-workshop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gsans","download_url":"https://codeload.github.com/gsans/code-chrysalis-workshop/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244880658,"owners_count":20525515,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","awsamplify","awsamplifyclient","awsappsync"],"created_at":"2024-10-14T01:48:21.754Z","updated_at":"2025-03-21T23:13:47.091Z","avatar_url":"https://github.com/gsans.png","language":null,"readme":"# Building your first Fullstack Serverless App with AWS Amplify\n\nIn this workshop we'll learn how to build cloud-enabled web applications with Angular \u0026 [AWS Amplify](https://aws-amplify.github.io/).\n\n![](https://i.imgur.com/GW1Nk5B.png)\n\n### Topics we'll be covering:\n\n- [Authentication](https://github.com/gsans/aws-amplify-workshop-angular#adding-authentication)\n- [GraphQL API with AWS AppSync](https://github.com/gsans/aws-amplify-workshop-angular#adding-a-graphql-api)\n- [Hosting](https://github.com/gsans/aws-amplify-workshop-angular#hosting)\n- [Multiple Environments](https://github.com/gsans/aws-amplify-workshop-react#working-with-multiple-environments)\n- [Deploying via the Amplify Console](https://github.com/gsans/aws-amplify-workshop-angular#amplify-console)\n- [Removing / Deleting Services](https://github.com/gsans/aws-amplify-workshop-angular#removing-services)\n\n## Pre-requisites\n\n- Node: `12.6.0`. Visit [Node](https://nodejs.org/en/download/)\n- npm: `6.9.0`. Packaged with Node otherwise run upgrade\n\n```bash\nnpm install -g npm\n```\n\n## Getting Started - Creating the Application\n\nTo get started, we first need to create a new Angular project \u0026 change into the new directory using the [Angular CLI](https://cli.angular.io/).\n\nIf you already have it installed, skip to the next step. If not, either install the CLI \u0026 create the app or create a new app using:\n\n```bash\nnpm install -g @angular/cli\nng new amplify-app\n```\n \nNow change into the new app directory and make sure it runs\n\n```bash\ncd amplify-app\nnpm install\nng serve\n```\n## Changes to Angular CLI project\n\nAdd type definitions for __Node__ by changing `tsconfig.app.json`. This is a requirement from `aws-js-sdk`.\n\n```json\n{\n  \"compilerOptions\": {\n    \"types\": [\"node\"]\n  },\n}\n```\n\nAdd the following code, to the top of `src/polyfills.ts`. This is a requirement for Angular 6+.\n\n```js\n(window as any).global = window;\n\n(window as any).process = {\n  env: { DEBUG: undefined }\n};\n```\n\n## Installing the CLI \u0026 Initializing a new AWS Amplify Project\n\nLet's now install the AWS Amplify API \u0026 AWS Amplify Angular library:\n\n```bash\nnpm install --save @aws-amplify/auth aws-amplify-angular\n```\n\n### Installing the AWS Amplify CLI\n\nNext, we'll install the AWS Amplify CLI:\n\n```bash\nnpm install -g @aws-amplify/cli\n```\n\nNow we need to configure the CLI with our credentials:\n\n```js\namplify configure\n```\n\n\u003e If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U).\n\nHere we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue:\n- Specify the AWS Region: __ap-northeast-1(Tokyo)__\n- Specify the username of the new IAM user: __amplify-app__\n\u003e In the AWS Console, click __Next: Permissions__, __Next: Tags__, __Next: Review__, \u0026 __Create User__ to create the new IAM user. Then, return to the command line \u0026 press Enter.\n- Enter the access key of the newly created user:   \n  accessKeyId: __(\u003cYOUR_ACCESS_KEY_ID\u003e)__   \n  secretAccessKey:  __(\u003cYOUR_SECRET_ACCESS_KEY\u003e)__\n- Profile Name: __default__\n\n\u003e 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.\n\n### Initializing A New Project\n\n```bash\namplify init\n```\n\n- Enter a name for the project: __amplify-app__\n- Enter a name for the environment: __dev__\n- Choose your default editor: __Visual Studio Code__   \n- Please choose the type of app that you're building __javascript__   \n- What javascript framework are you using __angular__   \n- Source Directory Path: __src__   \n- Distribution Directory Path: __dist/amplify-app__   \n- Build Command: __npm run-script build__   \n- Start Command: __ng serve__\n- Please choose the profile you want to use: __default__\n- Do you want to use an AWS profile? __Yes__\n- Please choose the profile you want to use __default__\n\nNow, the AWS Amplify CLI has iniatilized a new project \u0026 you will see a new folder: __amplify__. The files in this folder hold your project configuration.\n\n```bash\n\u003camplify-app\u003e\n    |_ amplify\n      |_ .config\n      |_ #current-cloud-backend\n      |_ backend\n      team-provider-info.json\n```\n\n## Adding Authentication\n\nTo add authentication to our Amplify project, we can use the following command:\n\n```sh\namplify add auth\n```\n\n\u003e When prompted choose \n- Do you want to use default authentication and security configuration?: __Default configuration__\n- How do you want users to be able to sign in when using your Cognito User Pool?: __Username__\n- Do you want to configure advanced settings? __Yes, I want to make some additional changes.__\n- What attributes are required for signing up? (Press \u0026lt;space\u0026gt; to select, \u0026lt;a\u0026gt; to \ntoggle all, \u0026lt;i\u0026gt; to invert selection): __Email__\n- Do you want to enable any of the following capabilities? (Press \u0026lt;space\u0026gt; to select, \u0026lt;a\u0026gt; to toggle all, \u0026lt;i\u0026gt; to invert selection): __None__\n\nNow, we'll run the push command and the cloud resources will be created in our AWS account.\n\n```bash\namplify push\n```\n\nTo quickly check your newly created __Cognito User Pool__ you can run\n\n```bash\namplify status\n```\n\n\u003e 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.\n\n### Configuring the Angular Application\n\nNow, our resources are created \u0026 we can start using them!\n\nThe 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.\n\nTo configure the app, open __main.ts__ and add the following code below the last import:\n\n```js\nimport API from '@aws-amplify/auth';\nimport amplify from './aws-exports';\nAPI.configure(amplify);\n```\n\nNow, our app is ready to start using our AWS services.\n\n### Importing the Angular Module\n\nAdd the Amplify Module and Service to `src/app/app.module.ts`:\n\n```js\nimport { AmplifyAngularModule, AmplifyService } from 'aws-amplify-angular';\n\n@NgModule({\n  imports: [\n    AmplifyAngularModule\n  ],\n  providers: [\n    AmplifyService\n  ]\n});\n```\n\n### Using Amplify Service\n\nThe `AmplifyService` provides access to AWS Amplify core categories via Dependency Injection: auth, analytics, storage, api, cache, pubsub; and authentication state via Observables.\n\n### Using the Authenticator Component\n\nAWS Amplify provides UI components that you can use in your App. Let's add these components to the project\n\n```bash\nnpm i --save @aws-amplify/ui\n```\n\nAlso include these imports to the top of `styles.css`\n\n```css\n@import \"~@aws-amplify/ui/src/Theme.css\";\n@import \"~@aws-amplify/ui/src/Angular.css\";\n```\n\nIn order to use the Authenticator Component add it to __src/app.component.html__:\n\n```html\n\u003camplify-authenticator\u003e\u003c/amplify-authenticator\u003e\n```\n\nNow, 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 \u0026 sign in.\n\n\u003e 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.\n\nAlternatively we can also use\n\n```bash\namplify console auth\n```\n\n### Accessing User Data\n\nWe can access the user's info now that they are signed in by calling `currentAuthenticatedUser()` which returns a Promise.\n\n```js\nimport { AmplifyService } from 'aws-amplify-angular';\n\n@Component(...)\nexport class AppComponent {\n  constructor(public amplify: AmplifyService) {\n    amplify.auth().currentAuthenticatedUser().then(console.log)\n  }\n}\n```\n\n### Custom authentication strategies\n\nThe `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 \u0026 functions.\n\nLet's look at how we might create our own authentication flow.\n\nTo 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 \u0026 password.\n\nTo do this, we could create a form like:\n\n```html\n\u003cform [formGroup]=\"signup\" (ngSubmit)=\"onSignup(signup.value)\"\u003e\n  \u003cdiv\u003e\n    \u003clabel\u003eEmail: \u003c/label\u003e\n    \u003cinput type=\"email\" formControlName=\"email\"\u003e\n  \u003c/div\u003e\n  \u003cdiv\u003e\n    \u003clabel\u003ePassword: \u003c/label\u003e\n    \u003cinput type=\"password\" formControlName=\"password\"\u003e\n  \u003c/div\u003e\n  \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n\u003c/form\u003e\n```\n\nWe'd also need to have a method that signed up \u0026 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`, \u0026 `forgotPassword`. These functions return a promise so they need to be handled asynchronously.\n\n```js\nimport Auth from '@aws-amplify/auth';\n\nexport class SignupComponent implements OnInit {\n  public signup: FormGroup;\n\n  constructor(\n    private fb: FormBuilder,\n  ) { }\n\n  ngOnInit() {\n    this.signup = this.fb.group({\n      'email': ['', Validators.required],\n      'password': ['', Validators.required]\n    });\n  }\n\n  onSignup(value: any) {\n    const email = value.email, password = value.password;\n    Auth.signUp(email, password).then( _ =\u003e {\n      this.success = true;\n    }).catch(console.log);\n  }\n```\n\n## Adding a GraphQL API\n\nTo add a GraphQL API, we can use the following command:\n\n```sh\namplify add api\n```\n\nAnswer the following questions\n\n- Please select from one of the below mentioned services __GraphQL__\n- Provide API name: __RestaurantAPI__\n- Choose an authorization type for the API __API key__\n- Do you have an annotated GraphQL schema? __No__\n- Do you want a guided schema creation? __Yes__\n- What best describes your project: __Single object with fields (e.g., “Todo” with ID, name, description)__\n- Do you want to edit the schema now? __Yes__\n\n\u003e When prompted, update the schema to the following:   \n\n```graphql\ntype Restaurant @model {\n  id: ID!\n  clientId: String\n  name: String!\n  description: String!\n  city: String!\n}\n```\n\n\u003e Next, let's push the configuration to our account:\n\n```bash\namplify push\n```\n\n- Are you sure you want to continue? __Yes__\n- Do you want to generate code for your newly created GraphQL API __Yes__\n- Choose the code generation language target __typescript__\n- Enter the file name pattern of graphql queries, mutations and subscriptions __src/graphql/**/*.ts__\n- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions __Yes__\n- Enter maximum statement depth [increase from default if your schema is deeply nested] __2__\n- Enter the file name for the generated code __src/API.ts__\n\nNotice your __GraphQL endpoint__ and __API KEY__.\n\nThis step created a new AWS AppSync API. Use the command below to access the AWS AppSync dashboard. Make sure that your region is correct.\n\n```bash\namplify console api\n```\n\n- Please select from one of the below mentioned services __GraphQL__\n\n\n### Adding mutations from within the AWS AppSync Console\n\nIn the AWS AppSync console, on the left side click on Queries.\n\nExecute the following mutation to create a new restaurant in the API:\n\n```graphql\nmutation createRestaurant {\n  createRestaurant(input: {\n    name: \"Nobu\"\n    description: \"Great Sushi\"\n    city: \"New York\"\n  }) {\n    id name description city\n  }\n}\n```\n\nNow, let's query for the restaurant:\n\n```graphql\nquery listRestaurants {\n  listRestaurants {\n    items {\n      id\n      name\n      description\n      city\n    }\n  }\n}\n```\n\nWe can even add search / filter capabilities when querying:\n\n```graphql\nquery searchRestaurants {\n  listRestaurants(filter: {\n    city: {\n      contains: \"New York\"\n    }\n  }) {\n    items {\n      id\n      name\n      description\n      city\n    }\n  }\n}\n```\n\n### Interacting with the GraphQL API from our client application - Querying for data\n\nNow that the GraphQL API is created we can begin interacting with it!\n\nThe first thing we'll do is perform a query to fetch data from our API. \n\nTo do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.\n\n\u003e Read more about the __Amplify GraphQL Client__ [here](https://aws-amplify.github.io/docs/js/api#amplify-graphql-client).\n\nFirst, we will install the AWS Amplify API and PubSub libraries:\n\n```bash\nnpm install --save @aws-amplify/api @aws-amplify/pubsub\n```\n\nTo configure the app, open __main.ts__ and change the initial code to configure the new dependencies:\n\n```js\nimport Auth from '@aws-amplify/auth';\nimport API from '@aws-amplify/api';\nimport PubSub from '@aws-amplify/pubsub';\nimport amplify from './aws-exports';\nAuth.configure(amplify);\nAPI.configure(amplify);\nPubSub.configure(amplify);\n```\n\n```js\nimport { APIService } from '../API.service';\nimport { Restaurant } from './types/restaurant';\n\n@Component({\n  template: `\n    \u003cdiv\u003e\n      \u003cdiv *ngFor=\"let restaurant of restaurants\"\u003e\n        {{ restaurant.name }}\n      \u003c/div\u003e\n    \u003c/div\u003e`\n})\nexport class AppComponent implements OnInit {\n  restaurants: Array\u003cRestaurant\u003e;\n  constructor(public api: APIService) { }\n  ngOnInit() {\n    this.api.ListRestaurants().then(data =\u003e {\n      this.restaurants = data.items;\n    });\n  }\n}\n```\n\n## Performing mutations\n\n Now, let's look at how we can create mutations.\n\n```js\nimport { FormBuilder, FormGroup, Validators } from '@angular/forms';\nimport { createRestaurant } from '../../graphql/mutations'\n\n@Component(...)\nexport class HomeComponent implements OnInit {\n  public createForm: FormGroup;\n\n  constructor(private fb: FormBuilder) { }\n\n  async ngOnInit() {\n    this.createForm = this.fb.group({\n      'name': ['', Validators.required],\n      'description': ['', Validators.required],\n      'city': ['', Validators.required]\n    });\n    this.api.ListRestaurants().then(event =\u003e {\n      this.restaurants = event.items;\n    });\n  } \n  \n  public onCreate(restaurant: any) {\n    this.api.CreateRestaurant(restaurant).then(event =\u003e {\n      console.log('item created!');\n      this.createForm.reset();\n    })\n    .catch(e =\u003e {\n      console.log('error creating restaurant...', e);\n    });\n  }\n}\n```\n\n### GraphQL Subscriptions\n\nNext, let's see how we can create a subscription to subscribe to changes of data in our API.\n\nTo do so, we need to listen to the subscription, \u0026 update the state whenever a new piece of data comes in through the subscription.\n\n```js\n@Component(...)\nexport class HomeComponent implements OnInit {\n  ngOnInit() {\n    this.api.OnCreateRestaurantListener.subscribe(event =\u003e {\n      const newRestaurant = event.value.data.onCreateRestaurant;\n      this.restaurants = [newRestaurant, ...this.restaurants];\n    });\n  }\n}\n```\n\n## Hosting\n\nTo deploy \u0026 host your app on AWS, we can use the `hosting` category.\n\n```sh\namplify add hosting\n```\n\n- Select the environment setup: __DEV (S3 only with HTTP)__\n- hosting bucket name __YOURBUCKETNAME__\n- index doc for the website __index.html__\n- error doc for the website __index.html__\n\nNow, everything is set up \u0026 we can publish it:\n\n```sh\namplify publish\n```\n\n## Working with multiple environments\n\nYou can create multiple environments for your application in which to create \u0026 test out new features without affecting the main environment which you are working on.\n\nWhen 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 \u0026 merge only the changes that have been made since the new environment was created back into the original environment.\n\nLet'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.\n\nFirst, we'll initialize a new environment using `amplify init`:\n\n```sh\namplify init\n```\n\n- Do you want to use an existing environment? __N__\n- Enter a name for the environment: __apiupdate__\n- Do you want to use an AWS profile? __Y__\n- __amplify-workshop-user__\n\nOnce the new environment is initialized, we should be able to see some information about our environment setup by running:\n\n```sh\namplify env list\n\n| Environments |\n| ------------ |\n| dev          |\n| *apiupdate   |\n```\n\nNow we can update the GraphQL Schema in `amplify/backend/api/RestaurantAPI/schema.graphql` to the following (adding the owner field):\n\n```graphql\ntype Restaurant @model {\n  ...\n  owner: String\n}\n```\n\nNow, we can create this new stack by running `amplify push`:\n\n```sh\namplify push\n```\n\nAfter we test it out, we can now merge it into our original dev environment:\n\n```sh\namplify env checkout dev\n\namplify status\n\namplify push\n```\n\n- Do you want to update code for your updated GraphQL API? __Y__\n- Do you want to generate GraphQL statements? __Y__\n\n\n## Deploying via the Amplify Console\n\nWe 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.\n\nThe 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 \u0026 initialize git in our local project:\n\n```sh\ngit init\n\ngit remote add origin git@github.com:username/project-name.git\n\ngit add .\n\ngit commit -m 'initial commit'\n\ngit push origin master\n```\n\nNext we'll visit the Amplify Console in our AWS account at [https://ap-northeast-1.console.aws.amazon.com/amplify/home](https://ap-northeast-1.console.aws.amazon.com/amplify/home).\n\nHere, we'll click __Get Started__ to create a new deployment. Next, authorize Github as the repository service.\n\nNext, we'll choose the new repository \u0026 branch for the project we just created \u0026 click __Next__.\n\nIn the next screen, we'll create a new role \u0026 use this role to allow the Amplify Console to deploy these resources \u0026 click __Next__.\n\nFinally, we can click __Save and Deploy__ to deploy our application!\n\nNow, we can push updates to Master to update our application.\n\n\n## Removing Services\n\nIf at any time, or at the end of this workshop, you would like to delete a service from your project \u0026 your account, you can do this by running the `amplify remove` command:\n\n```sh\namplify remove auth\n\namplify push\n```\n\nIf you are unsure of what services you have enabled at any time, you can run the `amplify status` command:\n\n```sh\namplify status\n```\n\n`amplify status` will give you the list of resources that are currently enabled in your app.\n\n\n## Appendix\n\n### Setup your AWS Account\n\nIn order to follow this workshop you need to create and activate an Amazon Web Services account. \n\nFollow the steps [here](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account)\n\n### Trobleshooting\n\nMessage: The AWS Access Key Id needs a subscription for the service\n\nSolution: Make sure you are subscribed to the free plan. [Subscribe](https://portal.aws.amazon.com/billing/signup?type=resubscribe#/resubscribed)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsans%2Fcode-chrysalis-workshop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgsans%2Fcode-chrysalis-workshop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsans%2Fcode-chrysalis-workshop/lists"}