这可能是由于WebSocket连接过程中网络问题导致的。可以通过重新连接WebSocket来解决该问题。以下是一个示例代码,通过在应用程序中引用该代码来解决此问题。
import Observable from 'zen-observable';
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync';
import awsconfig from './aws-exports';
const client = new AWSAppSyncClient({
url: awsconfig.aws_appsync_graphqlEndpoint,
region: awsconfig.aws_appsync_region,
auth: {
type: AUTH_TYPE.API_KEY,
apiKey: awsconfig.aws_appsync_apiKey,
},
// Enable offline support
offlineConfig: {
callback: (err, succ) => {
if (err) {
console.error('Unable to write to offline storage', err)
} else {
console.log('Successfully wrote to offline storage:', succ)
}
}
},
// Add retry on 401
// Adding this function to make subscription getting reconnected on 401 received on server
fetchPolicy: 'cache-and-network',
onError: ({ networkError, operation, forward }) => {
if (networkError.statusCode === 401) {
const { operation: op, variables } = operation;
op.query.definitions.forEach((definition) => {
if (definition.kind === "OperationDefinition") {
const { selectionSet } = definition;
definition.selectionSet.selections.forEach((selection) => {
if (selection.name.value === "onUpdateFeed") {
const table = selection.selectionSet.selections[0].name.value;
client.hydrated().then((client) => {
// Retry with the new token
client.subscribe({
query: operation.query,
variables: variables,
fetchPolicy: 'network-only'
});
})
}
})
}
})
}
},
});
const observable = Observable.create(observer => {
const realtimeResults = client.subscribe({
query: gql`subscription TestSubscription {
onCreatePost {
id
title
user {
id
name
}
}