首页 > 解决方案 > 为什么 AWSAppSyncClient 抛出错误网络错误:在 lambda 上离线时缺少乐观响应?

问题描述

lambda 正在调用 AWSAppSync 突变。它的行为不稳定。有时它会抛出下面提到的错误

错误:网络错误:离线时缺少乐观响应。

这是初始化 AWSAppSyncClient 的客户端对象的代码段。

 client = new AWSAppSyncClient({
        url: settings.url,
        region: settings.region,
        auth: {
            type: type,
            apiKey: settings.apiKey,
        },
        disableOffline: false
    });

似乎 lambda 和 AppSync 之间的连接在发生突变时丢失了。

 client.hydrated().then((client,error) => { 
         client.mutate({ 
                mutation: updateMutation, 
                variables: { 
                    ID: vehicle.VehicleID
             }
         });
 });

- 在 lambda 中使用 appsync 的原因是为了进行突变,所有订阅者都将获得突变的更新。

详细的错误日志

{ Error: Network error: Missing optimisticResponse while offline.
at new ApolloError (/var/task/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:124:32)
at Object.error (/var/task/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1088:32)
at notifySubscription (/var/task/node_modules/zen-observable/lib/Observable.js:130:18)
at onNotify (/var/task/node_modules/zen-observable/lib/Observable.js:161:3)
at SubscriptionObserver.error (/var/task/node_modules/zen-observable/lib/Observable.js:220:7)
at notifySubscription (/var/task/node_modules/zen-observable/lib/Observable.js:130:18)
at flushSubscription (/var/task/node_modules/zen-observable/lib/Observable.js:112:5)
at /var/task/node_modules/zen-observable/lib/Observable.js:156:14
at /var/task/node_modules/zen-observable/lib/Observable.js:67:7
at <anonymous>
graphQLErrors: [],
networkError: Error: Missing optimisticResponse while offline.
at /var/task/node_modules/aws-appsync/lib/link/offline-link.js:80:35
at new Subscription (/var/task/node_modules/zen-observable/lib/Observable.js:179:34)
at Observable.subscribe (/var/task/node_modules/zen-observable/lib/Observable.js:258:14)
at /var/task/node_modules/aws-appsync/lib/client.js:151:55
at <anonymous>,
message: 'Network error: Missing optimisticResponse while offline.',
extraInfo: undefined }

标签: amazon-web-servicesaws-lambdaaws-appsync

解决方案


调用突变的正确方法是在突变方法中包含optimisticReponse 选项,如下所示。

client.mutate({ 
                mutation: updateMutation, 
                variables: tempVehicle,
                optimisticResponse: () => ({ 
                    updateDslvehicleStateMutation: 
                    {
                        ID: tempVehicle.ID,
                        OPP: tempVehicle.OPP,
                        CDC: tempVehicle.CDC,
                        MND: tempVehicle.MND,
                        loc: tempVehicle.loc,
                        CSP: tempVehicle.CSP,
                        __typename: 'UpdateVehicleInput'
                    }
                })
            })

mutate 方法中添加optimisticResponse 失败,Appsync 中执行mutation 失败。


推荐阅读