在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):awslabs/aws-mobile-appsync-sdk-js开源软件地址(OpenSource Url):https://github.com/awslabs/aws-mobile-appsync-sdk-js开源编程语言(OpenSource Language):TypeScript 99.1%开源软件介绍(OpenSource Introduction):AWS AppSync JavaScript SDK ·AWS AppSync is a fully managed service that makes it easy to develop GraphQL APIs by handling the heavy lifting of securely connecting to data sources like AWS DynamoDB, Lambda, and more. You can use any HTTP or GraphQL client to connect to a GraphQL API on AppSync. For front-end web and mobile development, we recommend using the Amplify clients which are optimized to connect to the AppSync backend.
AWS AppSync Links for Apollo V3If you would like to use the Apollo JavaScript client version 3 to connect to your AppSync GraphQL API, this repository (on the current stable branch) provides Apollo links to use the different AppSync authorization modes, and to setup subscriptions over web sockets. Please log questions for this client SDK in this repo and questions for the AppSync service in the official AWS AppSync forum .
Example usage of Apollo V3 links AWS AppSync JavaScript SDKThe Note: if you do not have any offline requirements in your app, we recommend using the Amplify libraries.
Installationnpmnpm install --save aws-appsync yarnyarn add aws-appsync React Native CompatibilityWhen using this library with React Native, you need to ensure you are using the correct version of the library based on your version of React Native. Take a look at the table below to determine what version to use.
If you are using React Native npm install --save @react-native-community/[email protected] @react-native-community/async-storage or yarn add @react-native-community/[email protected] @react-native-community/async-storage If you are using React Native npx pod-install UsagePlease visit the documentation with the Amplify Framework for detailed instructions.
React / React NativeFor more documentation on Using Authorization and Subscription links with Apollo Client V3 (No offline support)For versions of the Apollo client newer than 2.4.6 you can use custom links for Authorization and Subscriptions. Offline support is not available for these newer versions. The packages available are
import { createAuthLink } from "aws-appsync-auth-link";
import { createSubscriptionHandshakeLink } from "aws-appsync-subscription-link";
import {
ApolloProvider,
ApolloClient,
InMemoryCache,
HttpLink,
ApolloLink,
} from "@apollo/client";
import appSyncConfig from "./aws-exports";
/* The HTTPS endpoint of the AWS AppSync API
(e.g. *https://aaaaaaaaaaaaaaaaaaaaaaaaaa.appsync-api.us-east-1.amazonaws.com/graphql*).
[Custom domain names](https://docs.aws.amazon.com/appsync/latest/devguide/custom-domain-name.html) can also be supplied here (e.g. *https://api.yourdomain.com/graphql*).
Custom domain names can have any format, but must end with `/graphql`
(see https://graphql.org/learn/serving-over-http/#uris-routes). */
const url = appSyncConfig.aws_appsync_graphqlEndpoint;
const region = appSyncConfig.aws_appsync_region;
const auth = {
type: appSyncConfig.aws_appsync_authenticationType,
apiKey: appSyncConfig.aws_appsync_apiKey,
// jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. token object is obtained previously
// credentials: async () => credentials, // Required when you use IAM-based auth.
};
const httpLink = new HttpLink({ uri: url });
const link = ApolloLink.from([
createAuthLink({ url, region, auth }),
createSubscriptionHandshakeLink({ url, region, auth }, httpLink),
]);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const ApolloWrapper = ({ children }) => {
return <ApolloProvider client={client}>{children}</ApolloProvider>;
}; Queries and Subscriptions using Apollo V3import React, { useState, useEffect } from "react";
import { gql, useSubscription } from "@apollo/client";
import { useMutation, useQuery } from "@apollo/client";
import { v4 as uuidv4 } from "uuid";
const initialState = { name: "", description: "" };
const App = () => {
const LIST_TODOS = gql`
query listTodos {
listTodos {
items {
id
name
description
}
}
}
`;
const {
loading: listLoading,
data: listData,
error: listError,
} = useQuery(LIST_TODOS);
const CREATE_TODO = gql`
mutation createTodo($input: CreateTodoInput!) {
createTodo(input: $input) {
id
name
description
}
}
`;
// https://www.apollographql.com/docs/react/data/mutations/
const [addTodoMutateFunction, { error: createError }] =
useMutation(CREATE_TODO);
async function addTodo() {
try {
addTodoMutateFunction({ variables: { input: { todo } } });
} catch (err) {
console.log("error creating todo:", err);
}
}
const DELETE_TODO = gql`
mutation deleteTodo($input: DeleteTodoInput!) {
deleteTodo(input: $input) {
id
name
description
}
}
`;
const [deleteTodoMutateFunction] = useMutation(DELETE_TODO, {
refetchQueries: [LIST_TODOS, "listTodos"],
});
async function removeTodo(id) {
try {
deleteTodoMutateFunction({ variables: { input: { id } } });
} catch (err) {
console.log("error deleting todo:", err);
}
}
const CREATE_TODO_SUBSCRIPTION = gql`
subscription OnCreateTodo {
onCreateTodo {
id
name
description
}
}
`;
const { data: createSubData, error: createSubError } = useSubscription(
CREATE_TODO_SUBSCRIPTION
);
return (
// Render TODOs
);
};
export default App; Creating a client (Apollo V2)import AWSAppSyncClient from "aws-appsync";
import AppSyncConfig from "./aws-exports";
import { ApolloProvider } from "react-apollo";
import { Rehydrated } from "aws-appsync-react"; // this needs to also be installed when working with React
import App from "./App";
const client = new AWSAppSyncClient({
/* The HTTPS endpoint of the AWS AppSync API
(e.g. *https://aaaaaaaaaaaaaaaaaaaaaaaaaa.appsync-api.us-east-1.amazonaws.com/graphql*).
[Custom domain names](https://docs.aws.amazon.com/appsync/latest/devguide/custom-domain-name.html) can also be supplied here (e.g. *https://api.yourdomain.com/graphql*).
Custom domain names can have any format, but must end with `/graphql`
(see https://graphql.org/learn/serving-over-http/#uris-routes). */
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey,
// jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. Token object is obtained previously
// credentials: async () => credentials, // Required when you use IAM-based auth.
},
});
const WithProvider = () => (
<ApolloProvider client={client}>
<Rehydrated>
<App />
</Rehydrated>
</ApolloProvider>
);
export default WithProvider; Queriesimport gql from "graphql-tag";
import { graphql } from "react-apollo";
const listPosts = gql`
query listPosts {
listPosts {
items {
id
name
}
}
}
`;
class App extends Component {
render() {
return (
<div>
{this.props.posts.map((post, index) => (
<h2 key={post.id ? post.id : index}>{post.name}</h2>
))}
</div>
);
}
}
export default graphql(listPosts, {
options: {
fetchPolicy: "cache-and-network",
},
props: (props) => ({
posts: props.data.listPosts ? props.data.listPosts.items : [],
}),
})(App); Mutations & optimistic UI (with graphqlMutation helper)import gql from "graphql-tag";
import { graphql, compose } from "react-apollo";
import { graphqlMutation } from "aws-appsync-react";
const CreatePost = gql`
mutation createPost($name: String!) {
createPost(input: { name: $name }) {
name
}
}
`;
class App extends Component {
state = { name: "" };
onChange = (e) => {
this.setState({ name: e.target.value });
};
addTodo = () => this.props.createPost({ name: this.state.name });
render() {
return (
<div>
<input onChange={this.onChange} placeholder="Todo name" />
<button onClick={this.addTodo}>Add Todo</button>
{this.props.posts.map((post, index) => (
<h2 key={post.id ? post.id : index}>{post.name}</h2>
))}
</div>
);
}
}
export default compose(
graphql(listPosts, {
options: {
fetchPolicy: "cache-and-network",
},
props: (props) => ({
posts: props.data.listPosts ? props.data.listPosts.items : [],
}),
}),
graphqlMutation(CreatePost, listPosts, "Post")
)(App); Mutations & optimistic UI (without graphqlMutation helper)import gql from "graphql-tag";
import uuidV4 from "uuid/v4";
import { graphql, compose } from "react-apollo";
const CreatePost = gql`
mutation createPost($name: String!) {
createPost(input: { name: $name }) {
name
}
}
`;
class App extends Component {
state = { name: "" }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论