Giter Site home page Giter Site logo

aws-appsync-react-workshop's Introduction

Building real-time applications with React, GraphQL & AWS AppSync

In this workshop we'll learn how to build cloud-enabled web applications with React, AppSync, GraphQL, & AWS Amplify.

Topics we'll be covering:

Redeeming the AWS Credit

  1. Visit the AWS Console.
  2. In the top right corner, click on My Account.
  3. In the left menu, click Credits.

Getting Started - Creating the React Application

To get started, we first need to create a new React project using the Create React App CLI.

$ npx create-react-app my-amplify-app

Now change into the new app directory & install the AWS Amplify, AWS Amplify React, & uuid libraries:

$ cd my-amplify-app
$ npm install --save aws-amplify aws-amplify-react uuid
# or
$ yarn add aws-amplify aws-amplify-react uuid

Installing the CLI & Initializing a new AWS Amplify Project

Installing the CLI

Next, we'll install the AWS Amplify CLI:

$ npm install -g @aws-amplify/cli

Now we need to configure the CLI with our credentials:

$ amplify configure

If you'd like to see a video walkthrough of this configuration process, click here.

Here we'll walk through the amplify configure setup. Once you've signed in to the AWS console, continue:

  • Specify the AWS Region: us-east-1 || us-west-2 || eu-central-1
  • Specify the username of the new IAM user: amplify-workshop-user

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.

  • Enter the access key of the newly created user:
    ? accessKeyId: (<YOUR_ACCESS_KEY_ID>)
    ? secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
  • Profile Name: amplify-workshop-user

Initializing A New Project

$ amplify init
  • Enter a name for the project: amplifyreactapp
  • Enter a name for the environment: dev
  • Choose your default editor: Visual Studio Code (or your default editor)
  • Please choose the type of app that you're building javascript
  • What javascript framework are you using react
  • Source Directory Path: src
  • Distribution Directory Path: build
  • Build Command: npm run-script build
  • Start Command: npm run-script start
  • Do you want to use an AWS profile? Y
  • Please choose the profile you want to use: amplify-workshop-user

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.

To view the status of the amplify project at any time, you can run the Amplify status command:

$ amplify status

Configuring the React applicaion

Now, our resources are created & we can start using them!

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.

To configure the app, open src/index.js and add the following code below the last import:

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Now, our app is ready to start using our AWS services.

Adding a GraphQL API

To add a GraphQL API, we can use the following command:

$ amplify add api

? Please select from one of the above mentioned services: GraphQL
? Provide API name: ConferenceAPI
? Choose an authorization type for the API: API key
? Enter a description for the API key: <some description>
? After how many days from now the API key should expire (1-365): 365
? Do you want to configure advanced settings for the GraphQL API: No
? Do you have an annotated GraphQL schema? N 
? Do you want a guided schema creation? Y
? What best describes your project: Single object with fields
? Do you want to edit the schema now? (Y/n) Y

When prompted, update the schema to the following:

# amplify/backend/api/ConferenceAPI/schema.graphql

type Talk @model {
  id: ID!
  clientId: ID
  name: String!
  description: String!
  speakerName: String!
  speakerBio: String!
}

Local mocking and testing

To mock and test the API locally, you can run the mock command:

$ amplify mock api

? Choose the code generation language target: javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y
? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2

This should start an AppSync Mock endpoint:

AppSync Mock endpoint is running at http://10.219.99.136:20002

Open the endpoint in the browser to use the GraphiQL Editor.

From here, we can now test the API.

Performing mutations from within the local testing environment

Execute the following mutation to create a new talk in the API:

mutation createTalk {
  createTalk(input: {
    name: "Full Stack React"
    description: "Using React to build Full Stack Apps with GraphQL"
    speakerName: "Jennifer"
    speakerBio: "Software Engineer"
  }) {
    id name description speakerName speakerBio
  }
}

Now, let's query for the talks:

query listTalks {
  listTalks {
    items {
      id
      name
      description
      speakerName
      speakerBio
    }
  }
}

We can even add search / filter capabilities when querying:

query listTalksWithFilter {
  listTalks(filter: {
    description: {
      contains: "React"
    }
  }) {
    items {
      id
      name
      description
      speakerName
      speakerBio
    }
  }
}

Interacting with the GraphQL API from our client application - Querying for data

Now that the GraphQL API server is running we can begin interacting with it!

The first thing we'll do is perform a query to fetch data from our API.

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.

src/App.js

// src/App.js
import React from 'react';

// imports from Amplify library
import { API, graphqlOperation } from 'aws-amplify'

// import query definition
import { listTalks as ListTalks } from './graphql/queries'

class App extends React.Component {
  // define some state to hold the data returned from the API
  state = {
    talks: []
  }

  // execute the query in componentDidMount
  async componentDidMount() {
    try {
      const talkData = await API.graphql(graphqlOperation(ListTalks))
      console.log('talkData:', talkData)
      this.setState({
        talks: talkData.data.listTalks.items
      })
    } catch (err) {
      console.log('error fetching talks...', err)
    }
  }
  render() {
    return (
      <>
        {
          this.state.talks.map((talk, index) => (
            <div key={index}>
              <h3>{talk.speakerName}</h3>
              <h5>{talk.name}</h5>
              <p>{talk.description}</p>
            </div>
          ))
        }
      </>
    )
  }
}

export default App

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.

Feel free to add some styling here to your list if you'd like 😀

Next, test the app locally:

$ npm start

Performing mutations

Now, let's look at how we can create mutations.

To do so, we'll refactor our initial state in order to also hold our form fields and add an event handler.

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 })).

We also have state to work with the form inputs, for name, description, speakerName, and speakerBio.

// src/App.js
import React from 'react';

import { API, graphqlOperation } from 'aws-amplify'
// import uuid to create a unique client ID
import uuid from 'uuid/v4'

import { listTalks as ListTalks } from './graphql/queries'
// import the mutation
import { createTalk as CreateTalk } from './graphql/mutations'

const CLIENT_ID = uuid()

class App extends React.Component {
  // define some state to hold the data returned from the API
  state = {
    name: '', description: '', speakerName: '', speakerBio: '', talks: []
  }

  // execute the query in componentDidMount
  async componentDidMount() {
    try {
      const talkData = await API.graphql(graphqlOperation(ListTalks))
      console.log('talkData:', talkData)
      this.setState({
        talks: talkData.data.listTalks.items
      })
    } catch (err) {
      console.log('error fetching talks...', err)
    }
  }
  createTalk = async() => {
    const { name, description, speakerBio, speakerName } = this.state
    if (name === '' || description === '' || speakerBio === '' || speakerName === '') return

    const talk = { name, description, speakerBio, speakerName, clientId: CLIENT_ID }
    const talks = [...this.state.talks, talk]
    this.setState({
      talks, name: '', description: '', speakerName: '', speakerBio: ''
    })

    try {
      await API.graphql(graphqlOperation(CreateTalk, { input: talk }))
      console.log('item created!')
    } catch (err) {
      console.log('error creating talk...', err)
    }
  }
  onChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    })
  }
  render() {
    return (
      <>
        <input
          name='name'
          onChange={this.onChange}
          value={this.state.name}
          placeholder='name'
        />
        <input
          name='description'
          onChange={this.onChange}
          value={this.state.description}
          placeholder='description'
        />
        <input
          name='speakerName'
          onChange={this.onChange}
          value={this.state.speakerName}
          placeholder='speakerName'
        />
        <input
          name='speakerBio'
          onChange={this.onChange}
          value={this.state.speakerBio}
          placeholder='speakerBio'
        />
        <button onClick={this.createTalk}>Create Talk</button>
        {
          this.state.talks.map((talk, index) => (
            <div key={index}>
              <h3>{talk.speakerName}</h3>
              <h5>{talk.name}</h5>
              <p>{talk.description}</p>
            </div>
          ))
        }
      </>
    )
  }
}

export default App

Adding Authentication

Next, let's update the app to add authentication.

To add authentication, we can use the following command:

$ amplify add auth

? Do you want to use default authentication and security configuration? Default configuration 
? How do you want users to be able to sign in when using your Cognito User Pool? Username
? Do you want to configure advanced settings? No, I am done.   

Using the withAuthenticator component

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:

// src/App.js, import the new component
import { withAuthenticator } from 'aws-amplify-react'

Next, we'll wrap our default export (the App component) with the withAuthenticator HOC:

// src/App.js, change the default export to this:
export default withAuthenticator(App, { includeGreetings: true })

To deploy the authentication service and mock and test the app locally, you can run the mock command:

$ amplify mock

? Are you sure you want to continue? Yes

Next, to test it out in the browser:

npm start

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.

Accessing User Data

We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser() in componentDidMount.

import {API, graphqlOperation, /* new 👉 */ Auth} from 'aws-amplify'

async componentDidMount() {
  // add this code to componentDidMount
  const user = await Auth.currentAuthenticatedUser()
  console.log('user:', user)
  console.log('user info:', user.signInUserSession.idToken.payload)
}

Adding Authorization to the GraphQL API

Next we need to update the AppSync API to now use the newly created Cognito Authentication service as the authentication type.

To do so, we'll reconfigure the API:

$ amplify update api

? Please select from one of the below mentioned services: GraphQL   
? Choose the default authorization type for the API: Amazon Cognito User Pool
? Do you want to configure advanced settings for the GraphQL API: No, I am done

Next, we'll test out the API with authentication enabled:

$ amplify mock

Now, we can only access the API with a logged in user.

You'll notice an auth button in the GraphiQL explorer that will allow you to update the simulated user and their groups.

Fine Grained access control - Using the @auth directive

GraphQL Type level authorization with the @auth directive

For authorization rules, we can start using the @auth directive.

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?

We could add the following type to our GraphQL schema:

# amplify/backend/api/ConferenceAPI/schema.graphql

type Comment @model @auth(rules: [
  { allow: owner, ownerField: "createdBy", operations: [create, update, delete]},
  { allow: private, operations: [read] }
  ]) {
  id: ID!
  message: String
  createdBy: String
}

allow: owner - This allows us to set owner authorization rules.
allow: private - This allows us to set private authorization rules.

This would allow us to create comments that only the creator of the Comment could delete, but anyone could read.

Creating a comment:

mutation createComment {
  createComment(input:{
    message: "Cool talk"
  }) {
    id
    message
    createdBy
  }
}

Listing comments:

query listComments {
  listComments {
    items {
      id
      message
      createdBy
    }
  }
}

Updating a comment:

mutation updateComment {
  updateComment(input: {
    id: "59d202f8-bfc8-4629-b5c2-bdb8f121444a"
  }) {
    id 
    message
    createdBy
  }
}

If you try to update a comment from someone else, you will get an unauthorized error.

Relationships

What if we wanted to create a relationship between the Comment and the Talk? That's pretty easy. We can use the @connection directive:

# amplify/backend/api/ConferenceAPI/schema.graphql

type Talk @model {
  id: ID!
  clientId: ID
  name: String!
  description: String!
  speakerName: String!
  speakerBio: String!
  comments: [Comment] @connection(name: "TalkComments")
}

type Comment @model @auth(rules: [
  { allow: owner, ownerField: "createdBy", operations: [create, update, delete]},
  { allow: private, operations: [read] }
  ]) {
  id: ID!
  message: String
  createdBy: String
  talk: Talk @connection(name: "TalkComments")
}

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:

$ rm -r amplify/mock-data

Now, restart the server:

$ amplify mock

Now, we can create relationships between talks and comments. Let's test this out with the following operations:

mutation createTalk {
  createTalk(input: {
    id: "test-id-talk-1"
    name: "Talk 1"
    description: "Cool talk"
    speakerBio: "Cool gal"
    speakerName: "Jennifer"
  }) {
    id
    name
    description
  }
}

mutation createComment {
  createComment(input: {
    commentTalkId: "test-id-talk-1"
    message: "Great talk"
  }) {
    id message
  }
}

query listTalks {
  listTalks {
    items {
      id
      name
      description
      comments {
        items {
          message
          createdBy
        }
      }
    }
  }
}

If you'd like to read more about the @auth directive, check out the documentation here.

Groups

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.

# amplify/backend/api/ConferenceAPI/schema.graphql

type Talk @model @auth(rules: [
  { allow: groups, groups: ["Admin"] },
  { allow: private, operations: [read] }
  ]) {
  id: ID!
  clientId: ID
  name: String!
  description: String!
  speakerName: String!
  speakerBio: String!
  comments: [Comment] @connection(name: "TalkComments")
}

type Comment @model @auth(rules: [
  { allow: owner, ownerField: "createdBy", operations: [create, update, delete]},
  { allow: private, operations: [read] }
  ]) {
  id: ID!
  message: String
  createdBy: String
  talk: Talk @connection(name: "TalkComments")
}

Run the server:

$ amplify mock

Click on the auth button and add Admin the user's groups.

Now, you'll notice that only users in the Admin group can create, update, or delete a talk, but anyone can read it.

Lambda GraphQL Resolvers

Next, let's have a look at how to deploy a serverless function and use it as a GraphQL resolver.

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.

The API we will be working with is the CoinLore API that will allow us to query for cryptocurrency data.

To get started, we'll create the new function:

$ amplify add function

? Provide a friendly name for your resource to be used as a label for this category in the project: currencyfunction
? Provide the AWS Lambda function name: currencyfunction
? Choose the function template that you want to use: Hello world function
? Do you want to access other resources created in this project from your Lambda function? N
? Do you want to edit the local lambda function now? Y

Update the function with the following code:

// amplify/backend/function/currencyfunction/src/index.js
const axios = require('axios')

exports.handler = function (event, _, callback) {
  let apiUrl = `https://api.coinlore.com/api/tickers/?start=1&limit=10`

  if (event.arguments) { 
    const { start = 0, limit = 10 } = event.arguments
    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}`
  }

  axios.get(apiUrl)
    .then(response => callback(null, response.data.data))
    .catch(err => callback(err))
}

In the above function we've used the 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:

amplify/backend/function/currencyfunction/src/package.json

"dependencies": {
  // ...
  "axios": "^0.19.0",
},

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:

type Coin {
  id: String!
  name: String!
  symbol: String!
  price_usd: String!
}

type Query {
  getCoins(limit: Int start: Int): [Coin] @function(name: "currencyfunction-${env}")
}

Now the schema has been updated and the Lambda function has been created. To test it out, you can run the mock command:

$ amplify mock

In the query editor, run the following queries:

# basic request
query listCoins {
  getCoins {
    price_usd
    name
    id
    symbol
  }
}

# request with arguments
query listCoinsWithArgs {
  getCoins(limit:3 start: 10) {
    price_usd
    name
    id
    symbol
  }
}

This query should return an array of cryptocurrency information.

Deploying the Services

Next, let's deploy the AppSync GraphQL API and the Lambda function:

$ amplify push

? Do you want to generate code for your newly created GraphQL API? Y
? Choose the code generation language target: javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2

To view the new AWS AppSync API at any time after its creation, run the following command:

$ amplify console api

To view the Cognito User Pool at any time after its creation, run the following command:

$ amplify console auth

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.

Hosting via the Amplify Console

The Amplify Console is a hosting service with continuous integration and continuous deployment.

The first thing we need to do is create a new GitHub repo 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:

$ git init

$ git remote add origin [email protected]:username/project-name.git

$ git add .

$ git commit -m 'initial commit'

$ git push origin master

Next we'll visit the Amplify Console in our AWS account at https://us-east-1.console.aws.amazon.com/amplify/home.

Here, we'll click on the app that we deployed earlier.

Next, under "Frontend environments", authorize Github as the repository service.

Next, we'll choose the new repository & branch for the project we just created & click Next.

In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click Next.

Finally, we can click Save and Deploy to deploy our application!

Now, we can push updates to Master to update our application.

Amplify DataStore

To implement a GraphQL API with Amplify DataStore, check out the tutorial here

Removing Services

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:

$ amplify remove auth

$ amplify push

If you are unsure of what services you have enabled at any time, you can run the amplify status command:

$ amplify status

amplify status will give you the list of resources that are currently enabled in your app.

If you'd like to delete the entire project, you can run the delete command:

$ amplify delete

aws-appsync-react-workshop's People

Contributors

dabit3 avatar felixgeelhaar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-appsync-react-workshop's Issues

Subscription connection failed

I'm following the workshop in YouTube, and after adding GraphQL subscription I'm getting the following error:

WebSocket connection to 'ws://192.168.100.18:20002/graphql?header=eyJob3N0IjoiMTkyLjE2OC4xMDAuMTg6MjAwMDIiLCJ4LWFtei1kYXRlIjoiMjAyMDA0MTlUMTgxNjMzWiIsIngtYXBpLWtleSI6ImRhMi1mYWtlQXBpSWQxMjM0NTYifQ==&payload=e30=' failed: Error during WebSocket handshake: Unexpected response code: 404

And the following object error (stringified):

{
  "provider": {
    "_config": {
      "aws_project_region": "us-east-1",
      "aws_appsync_graphqlEndpoint": "http://192.168.100.18:20002/graphql",
      "aws_appsync_region": "us-east-1",
      "aws_appsync_authenticationType": "API_KEY",
      "aws_appsync_apiKey": "da2-fakeApiId123456",
      "aws_appsync_dangerously_connect_to_http_endpoint_for_testing": true
    },
    "socketStatus": 0,
    "keepAliveTimeout": 300000,
    "subscriptionObserverMap": {},
    "promiseArray": [],
    "awsRealTimeSocket": null
  },
  "error": {
    "errors": [
      {
        "message": "Connection failed: Connection handshake error"
      }
    ]
  }
}

Error is being thrown from
projectFolder/node_modules/zen-observable-ts/node_modules/zen-observable/lib/Observable.js

I've been updating the code while following the workshop in this repo.

EDIT:

I changed the logger used in the amplify module to be verbose, if it helps, this is what is printed out in the browser console:

log.js:24 [HMR] Waiting for update signal from WDS...
ConsoleLogger.ts:99 [DEBUG] 42:21.515 Amplify - component registered in amplify ƒ I18n() {}
ConsoleLogger.ts:99 [DEBUG] 42:21.526 Amplify - component registered in amplify AuthClass {userPool: null, user: null, currentUserCredentials: ƒ}userPool: nulluser: nullcurrentUserCredentials: ƒ ()arguments: (...)caller: (...)length: 0name: "bound "__proto__: ƒ ()[[TargetFunction]]: ƒ ()[[BoundThis]]: AuthClass[[BoundArgs]]: Array(0)_config: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_storage: Storage {length: 0}length: 0__proto__: Storage_storageSync: Promise {<resolved>: undefined}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: undefined__proto__: Object
ConsoleLogger.ts:91 [DEBUG] 42:21.528 InMemoryCache - now we start!
ConsoleLogger.ts:99 [DEBUG] 42:21.528 Amplify - component registered in amplify BrowserStorageCacheClass {config: {…}, cacheCurSizeKey: "aws-amplify-cacheCurSize", getItem: ƒ, setItem: ƒ, removeItem: ƒ}config: {keyPrefix: "aws-amplify-cache", capacityInBytes: 1048576, itemMaxSize: 210000, defaultTTL: 259200000, defaultPriority: 5, …}keyPrefix: "aws-amplify-cache"capacityInBytes: 1048576itemMaxSize: 210000defaultTTL: 259200000defaultPriority: 5warningThreshold: 0.8storage: Storage {length: 0}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: ObjectcacheCurSizeKey: "aws-amplify-cacheCurSize"getItem: ƒ ()setItem: ƒ ()removeItem: ƒ ()__proto__: StorageCache
ConsoleLogger.ts:99 [DEBUG] 42:21.540 Amplify - component registered in amplify AnalyticsClass {_config: {…}, _pluggables: Array(0), _disabled: false, _trackers: {…}, record: ƒ}_config: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: trueautoSessionRecord: true__proto__: Object_pluggables: [AWSPinpointProvider]_disabled: false_trackers: {}record: ƒ ()__proto__: Object
ConsoleLogger.ts:91 [DEBUG] 42:21.563 Storage - Create Storage Instance, debug
ConsoleLogger.ts:99 [DEBUG] 42:21.563 StorageClass - Storage Options {}aws_appsync_dangerously_connect_to_http_endpoint_for_testing: {}__proto__: Object__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.563 Amplify - component registered in amplify Storage {_config: {…}, _pluggables: Array(0), get: ƒ, put: ƒ, remove: ƒ, …}_config: {aws_appsync_dangerously_connect_to_http_endpoint_for_testing: {…}}aws_appsync_dangerously_connect_to_http_endpoint_for_testing: {}__proto__: Object_pluggables: [AWSS3Provider]get: ƒ ()put: ƒ ()remove: ƒ ()list: ƒ ()vault: Storage {_config: {…}, _pluggables: Array(1), get: ƒ, put: ƒ, remove: ƒ, …}configure: ƒ (options)__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.564 StorageClass - Storage Options {}
ConsoleLogger.ts:99 [DEBUG] 42:21.564 Amplify - component registered in amplify Storage {_config: {…}, _pluggables: Array(0), get: ƒ, put: ƒ, remove: ƒ, …}_config: {aws_appsync_dangerously_connect_to_http_endpoint_for_testing: {…}}aws_appsync_dangerously_connect_to_http_endpoint_for_testing: {level: "private"}__proto__: Object_pluggables: Array(1)0: AWSS3Provider_config: __proto__: Object__proto__: Objectlength: 1__proto__: Array(0)get: ƒ ()put: ƒ ()remove: ƒ ()list: ƒ ()__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.565 Amplify - component registered in amplify RestAPIClass {_api: null, _options: null}
ConsoleLogger.ts:99 [DEBUG] 42:21.565 RestAPI - API Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.572 PubSub - PubSub Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.573 Amplify - component registered in amplify PubSubClass {_options: null, _pluggables: Array(0), subscribe: ƒ}awsAppSyncProvider: (...)awsAppSyncRealTimeProvider: AWSAppSyncRealTimeProviderisSSLEnabled: falseoptions: Objectaws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_config: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: ObjectsocketStatus: 0keepAliveTimeout: 300000subscriptionObserverMap: Map(0) {}promiseArray: []awsRealTimeSocket: null__proto__: AbstractPubSubProvider_options: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_pluggables: []subscribe: ƒ ()_awsAppSyncRealTimeProvider: AWSAppSyncRealTimeProvider {_config: {…}, socketStatus: 0, keepAliveTimeout: 300000, subscriptionObserverMap: Map(0), promiseArray: Array(0), …}isSSLEnabled: falseoptions: Objectaws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_config: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}socketStatus: 0keepAliveTimeout: 300000subscriptionObserverMap: Map(0) {}promiseArray: []awsRealTimeSocket: null__proto__: AbstractPubSubProvider__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.573 Amplify - component registered in amplify GraphQLAPIClass {_api: null, _options: null}
ConsoleLogger.ts:99 [DEBUG] 42:21.574 GraphQLAPI - API Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.574 Amplify - component registered in amplify RestAPIClass {_api: null, _options: null}
ConsoleLogger.ts:99 [DEBUG] 42:21.574 RestAPI - API Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.575 Amplify - component registered in amplify GraphQLAPIClass {_api: null, _options: null}
ConsoleLogger.ts:99 [DEBUG] 42:21.575 GraphQLAPI - API Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.575 Amplify - component registered in amplify APIClass {_options: null, _restApi: RestAPIClass, _graphqlApi: GraphQLAPIClass}_options: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_restApi: RestAPIClass {_api: RestClient, _options: {…}}_api: RestClient_region: "us-east-1"_service: "execute-api"_custom_header: undefined_options: aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: trueregion: "us-east-1"header: {}endpoints: []__proto__: Object__proto__: Object_options: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}__proto__: Object_graphqlApi: GraphQLAPIClass_api: RestClient_region: "us-east-1"_service: "execute-api"_custom_header: undefined_options: aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: trueregion: "us-east-1"header: {}__proto__: Object__proto__: Objectajax: ƒ (url, method, init)get: ƒ (url, init)put: ƒ (url, init)patch: ƒ (url, init)post: ƒ (url, init)del: ƒ (url, init)head: ƒ (url, init)endpoint: ƒ (apiName)_signed: ƒ (params, credentials, isAllResponse)_request: ƒ (params, isAllResponse)_parseUrl: ƒ (url)constructor: ƒ RestClient(options)__proto__: Object_options: aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: trueregion: "us-east-1"header: {}__proto__: Object__proto__: Object__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.576 API - API Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.577 Interactions - Interactions Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.577 Amplify - component registered in amplify InteractionsClass {_options: null, _pluggables: {…}}_options: bots: {}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_pluggables: {}__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.578 XR - XR Options null
ConsoleLogger.ts:99 [DEBUG] 42:21.579 AbstractXRProvider - configure SumerianProvider {}__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.580 Amplify - component registered in amplify XRClass {_options: null, _defaultProvider: "SumerianProvider", _pluggables: {…}}_options: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_defaultProvider: "SumerianProvider"_pluggables: SumerianProvider: SumerianProvideroptions: Objectaws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object_config: {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}aws_project_region: "us-east-1"aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql"aws_appsync_region: "us-east-1"aws_appsync_authenticationType: "API_KEY"aws_appsync_apiKey: "da2-fakeApiId123456"aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true__proto__: Object__proto__: AbstractXRProvider__proto__: Object__proto__: Object
ConsoleLogger.ts:99 [DEBUG] 42:21.580 Amplify - no getModuleName method for component XRClass {_options: null, _defaultProvider: "SumerianProvider", _pluggables: {…}}
ConsoleLogger.ts:99 [DEBUG] 42:21.581 Amplify - component registered in amplify PredictionsClass {_options: {…}, _convertPluggables: Array(0), _identifyPluggables: Array(0), _interpretPluggables: Array(0)}

// console.logs added by me in node_modules
PubSub.ts:93 configure PubSub.this._options {aws_project_region: "us-east-1", aws_appsync_graphqlEndpoint: "http://192.168.100.18:20002/graphql", aws_appsync_region: "us-east-1", aws_appsync_authenticationType: "API_KEY", aws_appsync_apiKey: "da2-fakeApiId123456", …}
PubSub.ts:95 configure PubSub.this._pluggables []
GraphQLAPI.ts:196 GraphQLAPIClass.prototype.graphql.operationType subscription

AWSAppSyncRealTimeProvider.ts:637 WebSocket connection to 'ws://192.168.100.18:20002/graphql?header=eyJob3N0IjoiMTkyLjE2OC4xMDAuMTg6MjAwMDIiLCJ4LWFtei1kYXRlIjoiMjAyMDA0MjBUMDE0MjIxWiIsIngtYXBpLWtleSI6ImRhMi1mYWtlQXBpSWQxMjM0NTYifQ==&payload=e30=' failed: Error during WebSocket handshake: Unexpected response code: 404
(anonymous) @ AWSAppSyncRealTimeProvider.ts:637
(anonymous) @ AWSAppSyncRealTimeProvider.ts:636
(anonymous) @ AWSAppSyncRealTimeProvider.ts:649
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
push../node_modules/@aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter @ AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._initializeHandshake @ AWSAppSyncRealTimeProvider.ts:630
(anonymous) @ Retry.ts:37
step @ Reachability.ts:25
(anonymous) @ Reachability.ts:25
(anonymous) @ Reachability.ts:25
push../node_modules/@aws-amplify/core/lib-esm/Util/Retry.js.__awaiter @ Reachability.ts:25
retry @ Retry.ts:26
jitteredExponentialRetry @ Retry.ts:78
(anonymous) @ AWSAppSyncRealTimeProvider.ts:623
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
push../node_modules/@aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter @ AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._initializeRetryableHandshake @ AWSAppSyncRealTimeProvider.ts:621
(anonymous) @ AWSAppSyncRealTimeProvider.ts:597
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
fulfilled @ AWSAppSyncProvider.ts:204

(5) AWSAppSyncRealTimeProvider.ts:637 WebSocket connection to 'ws://192.168.100.18:20002/graphql?header=eyJob3N0IjoiMTkyLjE2OC4xMDAuMTg6MjAwMDIiLCJ4LWFtei1kYXRlIjoiMjAyMDA0MjBUMDE0MjIxWiIsIngtYXBpLWtleSI6ImRhMi1mYWtlQXBpSWQxMjM0NTYifQ==&payload=e30=' failed: Error during WebSocket handshake: Unexpected response code: 404
(anonymous) @ AWSAppSyncRealTimeProvider.ts:637
(anonymous) @ AWSAppSyncRealTimeProvider.ts:636
(anonymous) @ AWSAppSyncRealTimeProvider.ts:649
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
push../node_modules/@aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter @ AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._initializeHandshake @ AWSAppSyncRealTimeProvider.ts:630
(anonymous) @ Retry.ts:37
step @ Reachability.ts:25
(anonymous) @ Reachability.ts:25
(anonymous) @ Reachability.ts:25
push../node_modules/@aws-amplify/core/lib-esm/Util/Retry.js.__awaiter @ Reachability.ts:25
retry @ Retry.ts:26
(anonymous) @ Retry.ts:51
step @ Reachability.ts:25
(anonymous) @ Reachability.ts:25
fulfilled @ Reachability.ts:25

Observable.js:65 Uncaught {provider: AWSAppSyncRealTimeProvider, error: {…}}
(anonymous) @ Observable.js:65
setTimeout (async)
hostReportError @ Observable.js:64
notifySubscription @ Observable.js:149
onNotify @ Observable.js:179
error @ Observable.js:240
error @ PubSub.ts:172
notifySubscription @ Observable.js:140
onNotify @ Observable.js:179
error @ Observable.js:240
(anonymous) @ AWSAppSyncRealTimeProvider.ts:294
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
rejected @ AWSAppSyncProvider.ts:204
Promise.then (async)
step @ AWSAppSyncProvider.ts:204
fulfilled @ AWSAppSyncProvider.ts:204
Promise.then (async)
step @ AWSAppSyncProvider.ts:204
fulfilled @ AWSAppSyncProvider.ts:204
Promise.then (async)
step @ AWSAppSyncProvider.ts:204
(anonymous) @ AWSAppSyncProvider.ts:204
push../node_modules/@aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter @ AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._startSubscriptionWithAWSAppSyncRealTime @ AWSAppSyncRealTimeProvider.ts:227
(anonymous) @ AWSAppSyncRealTimeProvider.ts:185
Subscription @ Observable.js:197
subscribe @ Observable.js:279
(anonymous) @ PubSub.ts:168
(anonymous) @ PubSub.ts:166
Subscription @ Observable.js:197
subscribe @ Observable.js:279
(anonymous) @ App.js:48
commitHookEffectListMount @ react-dom.development.js:19731
commitPassiveHookEffects @ react-dom.development.js:19769
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
flushPassiveEffectsImpl @ react-dom.development.js:22853
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushPassiveEffects @ react-dom.development.js:22820
(anonymous) @ react-dom.development.js:22699
workLoop @ scheduler.development.js:597
flushWork @ scheduler.development.js:552
performWorkUntilDeadline @ scheduler.development.js:164

error with amplify mock after adding lambda function resolver

I'm pretty sure amplify mock worked for me yesterday, because I was able to use the graphQL interface to get the coins, but when i try to run it today, i get this error

Creating table CommentTable locally
Failed to start API Mock endpoint Error: Lambda function currencyfunction does not exist in your project.
Please run amplify add function

I ran into this same problem on my own project a few days ago. Commented on the closest issue I could find.

aws-amplify/amplify-cli#2280

Thanks for the great workshops!! :)

UUID import in src/App.js

In the Performing mutations chapter, for the UUID import of src/App.js:
import uuid from 'uuid/v4'

I got an error when compiling (npm start):

Failed to compile.
./src/App.js
Module not found: Can't resolve 'uuid/v4' in '/Users/x/my-amplify-app/src'

I replaced the import with this syntax, and it's working:
import {v4 as uuid} from "uuid";

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.