├── .gitignore ├── AppWithHooks.js ├── README.md ├── appsync_header.jpg ├── dashboard1.jpg └── dashboard2.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | amplify-web-workshop 2 | 3 | amplify-demos/.gitignore 4 | amplify-demos/amplify 5 | amplify-demos/.amplifyrc 6 | amplify-demos/src/aws-exports.js 7 | amplify-demos/node_modules -------------------------------------------------------------------------------- /AppWithHooks.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | useEffect, useReducer 3 | } from 'react' 4 | 5 | import uuid from 'uuid/v4' 6 | import { API, graphqlOperation } from 'aws-amplify' 7 | import { listTalks} from './graphql/queries' 8 | import { createTalk } from './graphql/mutations' 9 | import { onCreateTalk } from './graphql/subscriptions' 10 | 11 | const CLIENTID = uuid() 12 | 13 | const initialState = { 14 | error: null, 15 | talks: [], 16 | name: '', description: '', speakerName: '', speakerBio: '' 17 | } 18 | 19 | function reducer(state, action) { 20 | switch(action.type) { 21 | case 'set': 22 | return { 23 | ...state, talks: action.talks 24 | } 25 | case 'add': 26 | return { 27 | ...state, 28 | talks: [ 29 | ...state.talks, action.talk 30 | ] 31 | } 32 | case 'error': 33 | return { 34 | ...state, error: true 35 | } 36 | case 'updateInput': 37 | return { 38 | ...state, 39 | [action.inputValue]: action.value 40 | } 41 | default: 42 | new Error() 43 | } 44 | } 45 | 46 | async function getTalks(dispatch) { 47 | try { 48 | const talkData = await API.graphql(graphqlOperation(listTalks)) 49 | console.log('talkData:', talkData) 50 | dispatch({ 51 | type: 'set', 52 | talks: talkData.data.listTalks.items 53 | }) 54 | } catch (err) { 55 | dispatch({ type: 'error' }) 56 | console.log('error fetching talks...', err) 57 | } 58 | } 59 | 60 | const updater = (value, inputValue, dispatch) => { 61 | dispatch({ 62 | type: 'updateInput', 63 | value, 64 | inputValue 65 | }) 66 | } 67 | 68 | async function CreateTalk(state, dispatch) { 69 | const { name, description, speakerName, speakerBio } = state 70 | const talk = { 71 | name, 72 | description, 73 | speakerName, 74 | speakerBio, 75 | clientId: CLIENTID 76 | } 77 | 78 | const updatedTalkArray = [...state.talks, talk] 79 | dispatch({ 80 | type: 'set', 81 | talks: updatedTalkArray 82 | }) 83 | 84 | try { 85 | await API.graphql(graphqlOperation(createTalk, { 86 | input: talk 87 | })) 88 | console.log('item created!') 89 | } catch (err) { 90 | console.log('error creating talk...', err) 91 | } 92 | } 93 | 94 | function App() { 95 | const [state, dispatch] = useReducer(reducer, initialState) 96 | useEffect(() => { 97 | const subscriber = API.graphql(graphqlOperation(onCreateTalk)).subscribe({ 98 | next: eventData => { 99 | const talk = eventData.value.data.onCreateTalk 100 | if(CLIENTID === talk.clientId) return 101 | dispatch({ type: "add", talk }) 102 | } 103 | }) 104 | return () => subscriber.unsubscribe() 105 | }, []) 106 | 107 | useEffect(() => { 108 | getTalks(dispatch) 109 | }, []) 110 | console.log('state: ', state) 111 | return ( 112 |
113 | updater(e.target.value, 'name', dispatch)} 117 | value={state.name} 118 | /> 119 | updater(e.target.value, 'description', dispatch)} 123 | value={state.description} 124 | /> 125 | updater(e.target.value, 'speakerName', dispatch)} 129 | value={state.speakerName} 130 | /> 131 | updater(e.target.value, 'speakerBio', dispatch)} 134 | value={state.speakerBio} 135 | style={{ height: 50, margin: 5, backgroundColor: "#ddd" }} 136 | /> 137 | 140 | { 141 | state.talks.map((talk, index) => ( 142 |
143 |

{talk.name}

144 |

{talk.description}

145 |

{talk.speakerName}

146 |

{talk.speakerBio}

147 |
148 | )) 149 | } 150 |
151 | ) 152 | } 153 | const styles = { 154 | talk: { 155 | padding: 15, 156 | borderBottomWidth: 2 157 | }, 158 | container: { 159 | flex: 1, 160 | justifyContent: 'center', 161 | backgroundColor: '#F5FCFF', 162 | paddingTop: 80 163 | }, 164 | welcome: { 165 | fontSize: 20, 166 | textAlign: 'center', 167 | margin: 10, 168 | }, 169 | instructions: { 170 | textAlign: 'center', 171 | color: '#333333', 172 | marginBottom: 5, 173 | }, 174 | } 175 | 176 | export default App -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building real-time applications with React, GraphQL & AWS AppSync 2 | 3 | In this workshop we'll learn how to build cloud-enabled web applications with React, [AppSync](https://aws.amazon.com/appsync/), GraphQL, & [AWS Amplify](https://aws-amplify.github.io/). 4 | 5 | ![](./appsync_header.jpg) 6 | 7 | ### Topics we'll be covering: 8 | 9 | - [GraphQL API with AWS AppSync](https://github.com/dabit3/aws-appsync-react-workshop#adding-a-graphql-api) 10 | - [Mocking and Testing](https://github.com/dabit3/aws-appsync-react-workshop#local-mocking-and-testing) 11 | - [Authentication](https://github.com/dabit3/aws-appsync-react-workshop#adding-authentication) 12 | - [Adding Authorization to the AWS AppSync API](https://github.com/dabit3/aws-appsync-react-workshop#adding-authorization-to-the-graphql-api) 13 | - [Lambda Resolvers](https://github.com/dabit3/aws-appsync-react-workshop#lambda-graphql-resolvers) 14 | - [Deploying the Services](https://github.com/dabit3/aws-appsync-react-workshop#deploying-the-services) 15 | - [Hosting with the Amplify Console](https://github.com/dabit3/aws-appsync-react-workshop#hosting-via-the-amplify-console) 16 | - [Amplify DataStore](https://github.com/dabit3/aws-appsync-react-workshop#amplify-datastore) 17 | - [Deleting the resources](https://github.com/dabit3/aws-appsync-react-workshop#removing-services) 18 | 19 | ## Redeeming the AWS Credit 20 | 21 | 1. Visit the [AWS Console](https://console.aws.amazon.com/console). 22 | 2. In the top right corner, click on __My Account__. 23 | ![](dashboard1.jpg) 24 | 3. In the left menu, click __Credits__. 25 | ![](dashboard2.jpg) 26 | 27 | ## Getting Started - Creating the React Application 28 | 29 | To get started, we first need to create a new React project using the [Create React App CLI](https://github.com/facebook/create-react-app). 30 | 31 | ```bash 32 | $ npx create-react-app my-amplify-app 33 | ``` 34 | 35 | Now change into the new app directory & install the AWS Amplify, AWS Amplify React, & uuid libraries: 36 | 37 | ```bash 38 | $ cd my-amplify-app 39 | $ npm install --save aws-amplify aws-amplify-react uuid 40 | # or 41 | $ yarn add aws-amplify aws-amplify-react uuid 42 | ``` 43 | 44 | ## Installing the CLI & Initializing a new AWS Amplify Project 45 | 46 | ### Installing the CLI 47 | 48 | Next, we'll install the AWS Amplify CLI: 49 | 50 | ```bash 51 | $ npm install -g @aws-amplify/cli 52 | ``` 53 | 54 | Now we need to configure the CLI with our credentials: 55 | 56 | ```sh 57 | $ amplify configure 58 | ``` 59 | 60 | > If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U). 61 | 62 | Here we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue: 63 | - Specify the AWS Region: __us-east-1 || us-west-2 || eu-central-1__ 64 | - Specify the username of the new IAM user: __amplify-workshop-user__ 65 | > 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. 66 | - Enter the access key of the newly created user: 67 | ? accessKeyId: __()__ 68 | ? secretAccessKey: __()__ 69 | - Profile Name: __amplify-workshop-user__ 70 | 71 | ### Initializing A New Project 72 | 73 | ```bash 74 | $ amplify init 75 | ``` 76 | 77 | - Enter a name for the project: __amplifyreactapp__ 78 | - Enter a name for the environment: __dev__ 79 | - Choose your default editor: __Visual Studio Code (or your default editor)__ 80 | - Please choose the type of app that you're building __javascript__ 81 | - What javascript framework are you using __react__ 82 | - Source Directory Path: __src__ 83 | - Distribution Directory Path: __build__ 84 | - Build Command: __npm run-script build__ 85 | - Start Command: __npm run-script start__ 86 | - Do you want to use an AWS profile? __Y__ 87 | - Please choose the profile you want to use: __amplify-workshop-user__ 88 | 89 | Now, the AWS Amplify CLI has iniatilized a new project & you will see a new folder: __amplify__ & a new file called `aws-exports.js` in the __src__ directory. These files hold your project configuration. 90 | 91 | To view the status of the amplify project at any time, you can run the Amplify `status` command: 92 | 93 | ```sh 94 | $ amplify status 95 | ``` 96 | 97 | ### Configuring the React applicaion 98 | 99 | Now, our resources are created & we can start using them! 100 | 101 | The first thing we need to do is to configure our React 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. 102 | 103 | To configure the app, open __src/index.js__ and add the following code below the last import: 104 | 105 | ```js 106 | import Amplify from 'aws-amplify' 107 | import config from './aws-exports' 108 | Amplify.configure(config) 109 | ``` 110 | 111 | Now, our app is ready to start using our AWS services. 112 | 113 | ## Adding a GraphQL API 114 | 115 | To add a GraphQL API, we can use the following command: 116 | 117 | ```sh 118 | $ amplify add api 119 | 120 | ? Please select from one of the above mentioned services: GraphQL 121 | ? Provide API name: ConferenceAPI 122 | ? Choose an authorization type for the API: API key 123 | ? Enter a description for the API key: 124 | ? After how many days from now the API key should expire (1-365): 365 125 | ? Do you want to configure advanced settings for the GraphQL API: No 126 | ? Do you have an annotated GraphQL schema? N 127 | ? Do you want a guided schema creation? Y 128 | ? What best describes your project: Single object with fields 129 | ? Do you want to edit the schema now? (Y/n) Y 130 | ``` 131 | 132 | > When prompted, update the schema to the following: 133 | 134 | ```graphql 135 | # amplify/backend/api/ConferenceAPI/schema.graphql 136 | 137 | type Talk @model { 138 | id: ID! 139 | clientId: ID 140 | name: String! 141 | description: String! 142 | speakerName: String! 143 | speakerBio: String! 144 | } 145 | ``` 146 | 147 | ## Local mocking and testing 148 | 149 | To mock and test the API locally, you can run the `mock` command: 150 | 151 | ```sh 152 | $ amplify mock api 153 | 154 | ? Choose the code generation language target: javascript 155 | ? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js 156 | ? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y 157 | ? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2 158 | ``` 159 | 160 | This should start an AppSync Mock endpoint: 161 | 162 | ```sh 163 | AppSync Mock endpoint is running at http://10.219.99.136:20002 164 | ``` 165 | 166 | Open the endpoint in the browser to use the GraphiQL Editor. 167 | 168 | From here, we can now test the API. 169 | 170 | ### Performing mutations from within the local testing environment 171 | 172 | Execute the following mutation to create a new talk in the API: 173 | 174 | ```graphql 175 | mutation createTalk { 176 | createTalk(input: { 177 | name: "Full Stack React" 178 | description: "Using React to build Full Stack Apps with GraphQL" 179 | speakerName: "Jennifer" 180 | speakerBio: "Software Engineer" 181 | }) { 182 | id name description speakerName speakerBio 183 | } 184 | } 185 | ``` 186 | 187 | Now, let's query for the talks: 188 | 189 | ```graphql 190 | query listTalks { 191 | listTalks { 192 | items { 193 | id 194 | name 195 | description 196 | speakerName 197 | speakerBio 198 | } 199 | } 200 | } 201 | ``` 202 | 203 | We can even add search / filter capabilities when querying: 204 | 205 | ```graphql 206 | query listTalksWithFilter { 207 | listTalks(filter: { 208 | description: { 209 | contains: "React" 210 | } 211 | }) { 212 | items { 213 | id 214 | name 215 | description 216 | speakerName 217 | speakerBio 218 | } 219 | } 220 | } 221 | ``` 222 | 223 | ### Interacting with the GraphQL API from our client application - Querying for data 224 | 225 | Now that the GraphQL API server is running we can begin interacting with it! 226 | 227 | The first thing we'll do is perform a query to fetch data from our API. 228 | 229 | 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. 230 | 231 | #### src/App.js 232 | 233 | ```js 234 | // src/App.js 235 | import React from 'react'; 236 | 237 | // imports from Amplify library 238 | import { API, graphqlOperation } from 'aws-amplify' 239 | 240 | // import query definition 241 | import { listTalks as ListTalks } from './graphql/queries' 242 | 243 | class App extends React.Component { 244 | // define some state to hold the data returned from the API 245 | state = { 246 | talks: [] 247 | } 248 | 249 | // execute the query in componentDidMount 250 | async componentDidMount() { 251 | try { 252 | const talkData = await API.graphql(graphqlOperation(ListTalks)) 253 | console.log('talkData:', talkData) 254 | this.setState({ 255 | talks: talkData.data.listTalks.items 256 | }) 257 | } catch (err) { 258 | console.log('error fetching talks...', err) 259 | } 260 | } 261 | render() { 262 | return ( 263 | <> 264 | { 265 | this.state.talks.map((talk, index) => ( 266 |
267 |

{talk.speakerName}

268 |
{talk.name}
269 |

{talk.description}

270 |
271 | )) 272 | } 273 | 274 | ) 275 | } 276 | } 277 | 278 | export default App 279 | ``` 280 | 281 | In the above code we are using `API.graphql` to call the GraphQL API, and then taking the result from that API call and storing the data in our state. This should be the list of talks you created via the GraphiQL editor. 282 | 283 | #### Feel free to add some styling here to your list if you'd like 😀 284 | 285 | Next, test the app locally: 286 | 287 | ```sh 288 | $ npm start 289 | ``` 290 | 291 | ## Performing mutations 292 | 293 | Now, let's look at how we can create mutations. 294 | 295 | To do so, we'll refactor our initial state in order to also hold our form fields and add an event handler. 296 | 297 | We'll also be using the `API` class from amplify again, but now will be passing a second argument to `graphqlOperation` in order to pass in variables: `API.graphql(graphqlOperation(CreateTalk, { input: talk }))`. 298 | 299 | We also have state to work with the form inputs, for `name`, `description`, `speakerName`, and `speakerBio`. 300 | 301 | ```js 302 | // src/App.js 303 | import React from 'react'; 304 | 305 | import { API, graphqlOperation } from 'aws-amplify' 306 | // import uuid to create a unique client ID 307 | import uuid from 'uuid/v4' 308 | 309 | import { listTalks as ListTalks } from './graphql/queries' 310 | // import the mutation 311 | import { createTalk as CreateTalk } from './graphql/mutations' 312 | 313 | const CLIENT_ID = uuid() 314 | 315 | class App extends React.Component { 316 | // define some state to hold the data returned from the API 317 | state = { 318 | name: '', description: '', speakerName: '', speakerBio: '', talks: [] 319 | } 320 | 321 | // execute the query in componentDidMount 322 | async componentDidMount() { 323 | try { 324 | const talkData = await API.graphql(graphqlOperation(ListTalks)) 325 | console.log('talkData:', talkData) 326 | this.setState({ 327 | talks: talkData.data.listTalks.items 328 | }) 329 | } catch (err) { 330 | console.log('error fetching talks...', err) 331 | } 332 | } 333 | createTalk = async() => { 334 | const { name, description, speakerBio, speakerName } = this.state 335 | if (name === '' || description === '' || speakerBio === '' || speakerName === '') return 336 | 337 | const talk = { name, description, speakerBio, speakerName, clientId: CLIENT_ID } 338 | const talks = [...this.state.talks, talk] 339 | this.setState({ 340 | talks, name: '', description: '', speakerName: '', speakerBio: '' 341 | }) 342 | 343 | try { 344 | await API.graphql(graphqlOperation(CreateTalk, { input: talk })) 345 | console.log('item created!') 346 | } catch (err) { 347 | console.log('error creating talk...', err) 348 | } 349 | } 350 | onChange = (event) => { 351 | this.setState({ 352 | [event.target.name]: event.target.value 353 | }) 354 | } 355 | render() { 356 | return ( 357 | <> 358 | 364 | 370 | 376 | 382 | 383 | { 384 | this.state.talks.map((talk, index) => ( 385 |
386 |

{talk.speakerName}

387 |
{talk.name}
388 |

{talk.description}

389 |
390 | )) 391 | } 392 | 393 | ) 394 | } 395 | } 396 | 397 | export default App 398 | ``` 399 | 400 | ## Adding Authentication 401 | 402 | Next, let's update the app to add authentication. 403 | 404 | To add authentication, we can use the following command: 405 | 406 | ```sh 407 | $ amplify add auth 408 | 409 | ? Do you want to use default authentication and security configuration? Default configuration 410 | ? How do you want users to be able to sign in when using your Cognito User Pool? Username 411 | ? Do you want to configure advanced settings? No, I am done. 412 | ``` 413 | 414 | ### Using the withAuthenticator component 415 | 416 | To add authentication in the React app, we'll go into __src/App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `aws-amplify-react`: 417 | 418 | ```js 419 | // src/App.js, import the new component 420 | import { withAuthenticator } from 'aws-amplify-react' 421 | ``` 422 | 423 | Next, we'll wrap our default export (the App component) with the `withAuthenticator` HOC: 424 | 425 | ```js 426 | // src/App.js, change the default export to this: 427 | export default withAuthenticator(App, { includeGreetings: true }) 428 | ``` 429 | 430 | To deploy the authentication service and mock and test the app locally, you can run the `mock` command: 431 | 432 | ```sh 433 | $ amplify mock 434 | 435 | ? Are you sure you want to continue? Yes 436 | ``` 437 | 438 | Next, to test it out in the browser: 439 | 440 | ```sh 441 | npm start 442 | ``` 443 | 444 | 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. 445 | 446 | 447 | ### Accessing User Data 448 | 449 | We can access the user's info now that they are signed in by calling `Auth.currentAuthenticatedUser()` in `componentDidMount`. 450 | 451 | ```js 452 | import {API, graphqlOperation, /* new 👉 */ Auth} from 'aws-amplify' 453 | 454 | async componentDidMount() { 455 | // add this code to componentDidMount 456 | const user = await Auth.currentAuthenticatedUser() 457 | console.log('user:', user) 458 | console.log('user info:', user.signInUserSession.idToken.payload) 459 | } 460 | ``` 461 | 462 | ## Adding Authorization to the GraphQL API 463 | 464 | Next we need to update the AppSync API to now use the newly created Cognito Authentication service as the authentication type. 465 | 466 | To do so, we'll reconfigure the API: 467 | 468 | ```sh 469 | $ amplify update api 470 | 471 | ? Please select from one of the below mentioned services: GraphQL 472 | ? Choose the default authorization type for the API: Amazon Cognito User Pool 473 | ? Do you want to configure advanced settings for the GraphQL API: No, I am done 474 | ``` 475 | 476 | Next, we'll test out the API with authentication enabled: 477 | 478 | ```sh 479 | $ amplify mock 480 | ``` 481 | Now, we can only access the API with a logged in user. 482 | 483 | You'll notice an __auth__ button in the GraphiQL explorer that will allow you to update the simulated user and their groups. 484 | 485 | ### Fine Grained access control - Using the @auth directive 486 | 487 | #### GraphQL Type level authorization with the @auth directive 488 | 489 | For authorization rules, we can start using the `@auth` directive. 490 | 491 | What if you'd like to have a new `Comment` type that could only be updated or deleted by the creator of the `Comment` but can be read by anyone? 492 | 493 | We could add the following type to our GraphQL schema: 494 | 495 | ```graphql 496 | # amplify/backend/api/ConferenceAPI/schema.graphql 497 | 498 | type Comment @model @auth(rules: [ 499 | { allow: owner, ownerField: "createdBy", operations: [create, update, delete]}, 500 | { allow: private, operations: [read] } 501 | ]) { 502 | id: ID! 503 | message: String 504 | createdBy: String 505 | } 506 | ``` 507 | 508 | __allow: owner__ - This allows us to set owner authorization rules. 509 | __allow: private__ - This allows us to set private authorization rules. 510 | 511 | This would allow us to create comments that only the creator of the Comment could delete, but anyone could read. 512 | 513 | Creating a comment: 514 | 515 | ```graphql 516 | mutation createComment { 517 | createComment(input:{ 518 | message: "Cool talk" 519 | }) { 520 | id 521 | message 522 | createdBy 523 | } 524 | } 525 | ``` 526 | 527 | Listing comments: 528 | 529 | ```graphql 530 | query listComments { 531 | listComments { 532 | items { 533 | id 534 | message 535 | createdBy 536 | } 537 | } 538 | } 539 | ``` 540 | 541 | Updating a comment: 542 | 543 | ```graphql 544 | mutation updateComment { 545 | updateComment(input: { 546 | id: "59d202f8-bfc8-4629-b5c2-bdb8f121444a" 547 | }) { 548 | id 549 | message 550 | createdBy 551 | } 552 | } 553 | ``` 554 | 555 | If you try to update a comment from someone else, you will get an unauthorized error. 556 | 557 | ### Relationships 558 | 559 | What if we wanted to create a relationship between the Comment and the Talk? That's pretty easy. We can use the `@connection` directive: 560 | 561 | ```graphql 562 | # amplify/backend/api/ConferenceAPI/schema.graphql 563 | 564 | type Talk @model { 565 | id: ID! 566 | clientId: ID 567 | name: String! 568 | description: String! 569 | speakerName: String! 570 | speakerBio: String! 571 | comments: [Comment] @connection(name: "TalkComments") 572 | } 573 | 574 | type Comment @model @auth(rules: [ 575 | { allow: owner, ownerField: "createdBy", operations: [create, update, delete]}, 576 | { allow: private, operations: [read] } 577 | ]) { 578 | id: ID! 579 | message: String 580 | createdBy: String 581 | talk: Talk @connection(name: "TalkComments") 582 | } 583 | ``` 584 | 585 | Because we're updating the way our database is configured by adding relationships which requires a global secondary index, we need to delete the old local database: 586 | 587 | ```sh 588 | $ rm -r amplify/mock-data 589 | ``` 590 | 591 | Now, restart the server: 592 | 593 | ```sh 594 | $ amplify mock 595 | ``` 596 | 597 | Now, we can create relationships between talks and comments. Let's test this out with the following operations: 598 | 599 | ```graphql 600 | mutation createTalk { 601 | createTalk(input: { 602 | id: "test-id-talk-1" 603 | name: "Talk 1" 604 | description: "Cool talk" 605 | speakerBio: "Cool gal" 606 | speakerName: "Jennifer" 607 | }) { 608 | id 609 | name 610 | description 611 | } 612 | } 613 | 614 | mutation createComment { 615 | createComment(input: { 616 | commentTalkId: "test-id-talk-1" 617 | message: "Great talk" 618 | }) { 619 | id message 620 | } 621 | } 622 | 623 | query listTalks { 624 | listTalks { 625 | items { 626 | id 627 | name 628 | description 629 | comments { 630 | items { 631 | message 632 | createdBy 633 | } 634 | } 635 | } 636 | } 637 | } 638 | ``` 639 | 640 | If you'd like to read more about the `@auth` directive, check out the documentation [here](https://aws-amplify.github.io/docs/cli/graphql#auth). 641 | 642 | ### Groups 643 | 644 | The last problem we are facing is that *anyone* signed in can create a new talk. Let's add authorization that only allows users that are in an __Admin__ group to create and update talks. 645 | 646 | ```graphql 647 | # amplify/backend/api/ConferenceAPI/schema.graphql 648 | 649 | type Talk @model @auth(rules: [ 650 | { allow: groups, groups: ["Admin"] }, 651 | { allow: private, operations: [read] } 652 | ]) { 653 | id: ID! 654 | clientId: ID 655 | name: String! 656 | description: String! 657 | speakerName: String! 658 | speakerBio: String! 659 | comments: [Comment] @connection(name: "TalkComments") 660 | } 661 | 662 | type Comment @model @auth(rules: [ 663 | { allow: owner, ownerField: "createdBy", operations: [create, update, delete]}, 664 | { allow: private, operations: [read] } 665 | ]) { 666 | id: ID! 667 | message: String 668 | createdBy: String 669 | talk: Talk @connection(name: "TalkComments") 670 | } 671 | ``` 672 | 673 | Run the server: 674 | 675 | ```sh 676 | $ amplify mock 677 | ``` 678 | 679 | Click on the __auth__ button and add __Admin__ the user's groups. 680 | 681 | Now, you'll notice that only users in the __Admin__ group can create, update, or delete a talk, but anyone can read it. 682 | 683 | ## Lambda GraphQL Resolvers 684 | 685 | Next, let's have a look at how to deploy a serverless function and use it as a GraphQL resolver. 686 | 687 | The use case we will work with is fetching data from another HTTP API and returning the response via GraphQL. To do this, we'll use a serverless function. 688 | 689 | The API we will be working with is the CoinLore API that will allow us to query for cryptocurrency data. 690 | 691 | To get started, we'll create the new function: 692 | 693 | ```sh 694 | $ amplify add function 695 | 696 | ? Provide a friendly name for your resource to be used as a label for this category in the project: currencyfunction 697 | ? Provide the AWS Lambda function name: currencyfunction 698 | ? Choose the function template that you want to use: Hello world function 699 | ? Do you want to access other resources created in this project from your Lambda function? N 700 | ? Do you want to edit the local lambda function now? Y 701 | ``` 702 | 703 | Update the function with the following code: 704 | 705 | ```javascript 706 | // amplify/backend/function/currencyfunction/src/index.js 707 | const axios = require('axios') 708 | 709 | exports.handler = function (event, _, callback) { 710 | let apiUrl = `https://api.coinlore.com/api/tickers/?start=1&limit=10` 711 | 712 | if (event.arguments) { 713 | const { start = 0, limit = 10 } = event.arguments 714 | apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}` 715 | } 716 | 717 | axios.get(apiUrl) 718 | .then(response => callback(null, response.data.data)) 719 | .catch(err => callback(err)) 720 | } 721 | ``` 722 | 723 | In the above function we've used the [axios](https://github.com/axios/axios) library to call another API. In order to use __axios__, we need be sure that it will be installed by updating the package.json for the new function: 724 | 725 | __amplify/backend/function/currencyfunction/src/package.json__ 726 | 727 | ```json 728 | "dependencies": { 729 | // ... 730 | "axios": "^0.19.0", 731 | }, 732 | ``` 733 | Next, we'll update the GraphQL schema to add a new type and query. In amplify/backend/api/ConferenceAPI/schema.graphql, update the schema with the following new types: 734 | 735 | ```graphql 736 | type Coin { 737 | id: String! 738 | name: String! 739 | symbol: String! 740 | price_usd: String! 741 | } 742 | 743 | type Query { 744 | getCoins(limit: Int start: Int): [Coin] @function(name: "currencyfunction-${env}") 745 | } 746 | ``` 747 | 748 | Now the schema has been updated and the Lambda function has been created. To test it out, you can run the mock command: 749 | 750 | ```sh 751 | $ amplify mock 752 | ``` 753 | 754 | In the query editor, run the following queries: 755 | 756 | ```graphql 757 | # basic request 758 | query listCoins { 759 | getCoins { 760 | price_usd 761 | name 762 | id 763 | symbol 764 | } 765 | } 766 | 767 | # request with arguments 768 | query listCoinsWithArgs { 769 | getCoins(limit:3 start: 10) { 770 | price_usd 771 | name 772 | id 773 | symbol 774 | } 775 | } 776 | ``` 777 | 778 | This query should return an array of cryptocurrency information. 779 | 780 | ## Deploying the Services 781 | 782 | Next, let's deploy the AppSync GraphQL API and the Lambda function: 783 | 784 | ```bash 785 | $ amplify push 786 | 787 | ? Do you want to generate code for your newly created GraphQL API? Y 788 | ? Choose the code generation language target: javascript 789 | ? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js 790 | ? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y 791 | ? Enter maximum statement depth [increase from default if your schema is deeply nested] 2 792 | ``` 793 | 794 | To view the new AWS AppSync API at any time after its creation, run the following command: 795 | 796 | ```sh 797 | $ amplify console api 798 | ``` 799 | 800 | To view the Cognito User Pool at any time after its creation, run the following command: 801 | 802 | ```sh 803 | $ amplify console auth 804 | ``` 805 | 806 | To test an authenticated API out in the AWS AppSync console, it will ask for you to __Login with User Pools__. The form will ask you for a __ClientId__. This __ClientId__ is located in __src/aws-exports.js__ in the `aws_user_pools_web_client_id` field. 807 | 808 | ## Hosting via the Amplify Console 809 | 810 | The Amplify Console is a hosting service with continuous integration and continuous deployment. 811 | 812 | 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: 813 | 814 | ```sh 815 | $ git init 816 | 817 | $ git remote add origin git@github.com:username/project-name.git 818 | 819 | $ git add . 820 | 821 | $ git commit -m 'initial commit' 822 | 823 | $ git push origin master 824 | ``` 825 | 826 | Next we'll visit the Amplify Console in our AWS account at [https://us-east-1.console.aws.amazon.com/amplify/home](https://us-east-1.console.aws.amazon.com/amplify/home). 827 | 828 | Here, we'll click on the app that we deployed earlier. 829 | 830 | Next, under "Frontend environments", authorize Github as the repository service. 831 | 832 | Next, we'll choose the new repository & branch for the project we just created & click __Next__. 833 | 834 | In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click __Next__. 835 | 836 | Finally, we can click __Save and Deploy__ to deploy our application! 837 | 838 | Now, we can push updates to Master to update our application. 839 | 840 | ## Amplify DataStore 841 | 842 | To implement a GraphQL API with Amplify DataStore, check out the tutorial [here](https://github.com/dabit3/amplify-datastore-example) 843 | 844 | ## Removing Services 845 | 846 | 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: 847 | 848 | ```sh 849 | $ amplify remove auth 850 | 851 | $ amplify push 852 | ``` 853 | 854 | If you are unsure of what services you have enabled at any time, you can run the `amplify status` command: 855 | 856 | ```sh 857 | $ amplify status 858 | ``` 859 | 860 | `amplify status` will give you the list of resources that are currently enabled in your app. 861 | 862 | If you'd like to delete the entire project, you can run the `delete` command: 863 | 864 | ```sh 865 | $ amplify delete 866 | ``` 867 | 868 | -------------------------------------------------------------------------------- /appsync_header.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-appsync-react-workshop/82ac8aa74451ebbb273c006dfaca23b79bde2ace/appsync_header.jpg -------------------------------------------------------------------------------- /dashboard1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-appsync-react-workshop/82ac8aa74451ebbb273c006dfaca23b79bde2ace/dashboard1.jpg -------------------------------------------------------------------------------- /dashboard2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/aws-appsync-react-workshop/82ac8aa74451ebbb273c006dfaca23b79bde2ace/dashboard2.jpg --------------------------------------------------------------------------------