Using the AWS AppSync service allowed us to quickly create a usable GraphQL service without having to build the GraphQL service ourselves.
Lead requirements
We need an AWS account in the US (I have never tried in China).
What is a GraphQL
Liverpoolfc.tv: graphql.org/
GraphQL is an API query language and runtime that allows you to define the data you want to query.
Why GraphQL?
- Address front-end and back-end communication costs
- The front end can define the desired data fields
- Reduce network requests
- There are types of data
Install the AWS AppSync Cli tool
The official document: docs. Amplify. Aws/start/getti…
npm install -g @aws-amplify/cli
Copy the code
Create the React project
npx create-react-app graphql-demo
cd graphql-demo
amplify init
Copy the code
During the initialization process, you may need to jump to the AWS web site to log in and then generate the key operation
? Enter a name for the project graphqldemo The following configuration will be applied: Project information | Name: graphqldemo | Environment: dev | Default editor: Visual Studio Code | App type: javascript | Javascript framework: react | Source Directory Path: src | Distribution Directory Path: build | Build Command: npm run-script build | Start Command: npm run-script start ? Initialize the project with the above configuration? Yes Using default provider awscloudformation ? Select the authentication method you want to use: AWS profile For more information on AWS Profiles, see: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html ? Please choose the profile you want to use default Adding backend environment dev to AWS Amplify Console app: D27dte43jflp3w ⠧ Initializing Project in the cloud... Pro tip: Try "amplify add api" to create a backend API and then "amplify publish" to deploy everythingCopy the code
Create the GraphQL API and database
amplify add api
Copy the code
Select GraphQL, press enter, template select one-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
? Please select from one of the below mentioned services: GraphQL ? Provide API name: graphqldemo ? Choose the default authorization type for the API API key ? Enter a description for the API key: ? After how many days from now the API key should expire (1-365): 7 ? Do you want to configure advanced settings for the GraphQL API No, I am done. ? Do you have an annotated GraphQL schema? No ? Choose a schema template: One-to-many relationship (e.g., Blogs "with" Posts "and" Comments ") The following types do not have '@auth' enabled. Consider using @auth with @model - Blog - Post - Comment Learn more about @auth here: https://docs.amplify.aws/cli/graphql-transformer/auth GraphQL schema compiled successfully. Edit your schema at /Users/sunny/Desktop/hs/graphql-demo/amplify/backend/api/graphqldemo/schema.graphql or place .graphql files in a directory at /Users/sunny/Desktop/hs/graphql-demo/amplify/backend/api/graphqldemo/schema ? Do you want to edit the schema now? Yes ? Choose your default editor: Visual Studio Code Edit the file in your editor: /Users/sunny/Desktop/hs/graphql-demo/amplify/backend/api/graphqldemo/schema.graphql Successfully added resource graphqldemo locally Some next steps: "amplify push" will build all your local backend resources and provision it in the cloud "amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloudCopy the code
After the creation is successful, you can see the generated goodamplify/backend/api/graphqldemo/schema.graphql
file
type Blog @model {
id: ID!
name: String!
posts: [Post] @connection(keyName: "byBlog", fields: ["id"])
}
type Post @model @key(name: "byBlog", fields: ["blogID"]) {
id: ID!
title: String!
blogID: ID!
blog: Blog @connection(fields: ["blogID"])
comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}
type Comment @model @key(name: "byPost", fields: ["postID", "content"]) {
id: ID!
postID: ID!
post: Post @connection(fields: ["postID"])
content: String!
}
Copy the code
Deployed to the AWS
amplify push -y
Copy the code
Generated after the deployment is successfulaws-exports.js
Files andgraphql
folder
src/
graphql/
mutations.js
queries.js
schema.json
subscriptions.js
aws-exports.js
Copy the code
Next we call the GraphQL service in React and open app.js
import config from './aws-exports'
function App() {
// Create data
const createData = async() = > {const blogName = prompt('Please enter a blog name')
let data = await fetch(config.aws_appsync_graphqlEndpoint, {
method: 'POST'.headers: {
'X-Api-Key': config.aws_appsync_apiKey
},
body: JSON.stringify({
query: `mutation CreateBlog {
createBlog(input: {name: "${blogName}"}) {
id
name
}
}`,
})
})
data = await data.json()
console.log(data)
}
// Get the list of data
const pullData = async() = > {let data = await fetch(config.aws_appsync_graphqlEndpoint, {
method: 'POST'.headers: {
'X-Api-Key': config.aws_appsync_apiKey
},
body: JSON.stringify({
query: `query MyQuery { listBlogs { items { name posts { items { id title } } } } }`
})
})
data = await data.json()
console.log(data)
}
return (
<div className="App">
<button onClick={createData}>Create a blog</button>
<button onClick={pullData}>Blog list</button>
</div>
);
}
export default App;
Copy the code
Create a blog
Blog list
Call aws- Amplify to call the GraphQL service using the AWS – Amplify tool provided by AWS
npm install aws-amplify
Copy the code
Modify index.js to add the following code
import { Amplify } from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)
Copy the code
Modify the App. Js
import config from './aws-exports'
import { API } from 'aws-amplify'
import { listBlogs } from './graphql/queries'
import { createBlog } from './graphql/mutations'
import { onCreateBlog } from './graphql/subscriptions'
import { useEffect } from 'react'
function App() {
// Create data
const createData = async() = > {const blogName = prompt('Please enter a blog name')
let data = await fetch(config.aws_appsync_graphqlEndpoint, {
method: 'POST'.headers: {
'X-Api-Key': config.aws_appsync_apiKey
},
body: JSON.stringify({
query: `mutation CreateBlog {
createBlog(input: {name: "${blogName}"}) {
id
name
}
}`,
})
})
data = await data.json()
console.log(data)
}
// Get the list of data
const pullData = async() = > {let data = await fetch(config.aws_appsync_graphqlEndpoint, {
method: 'POST'.headers: {
'X-Api-Key': config.aws_appsync_apiKey
},
body: JSON.stringify({
query: `query MyQuery { listBlogs { items { name posts { items { id title } } } } }`
})
})
data = await data.json()
console.log(data)
}
// Aws creates blogs
const awsCreateBlog = async() = > {const blogName = prompt('Please enter a blog name')
const data = await API.graphql({ query: createBlog, variables: { input: { name: blogName }} })
console.log(data)
}
// aws gets the list of blogs
const awsListBlog = async() = > {const data = await API.graphql({ query: listBlogs })
console.log(data)
}
useEffect(() = > {
// Listen for blog creation events
const subscription = API.graphql({
query: onCreateBlog
}).subscribe({
next: data= > {
awsListBlog()
},
error: err= > {
console.log(err)
}
})
return () = > subscription.unsubscribe()
}, [])
return (
<div className="App">
<button onClick={createData}>Create a blog</button>
<button onClick={pullData}>Blog list</button>
<br/><br/>
<button onClick={awsCreateBlog}>Creating a blog in AWS</button>
</div>
);
}
export default App;
Copy the code
Create a blog
Blog list
So that’s pretty much the end of our demo. If you are interested in GraphQL, I will introduce it to you through the project.
Project source code: github.com/cmdfas/reac…