按示例配置时,节点环境中的 AWS AppSync 会发出有关 asyncLocalStorage 的错误

AWS AppSync in node environment spews errors about asyncLocalStorage when configured per example

以下 the example provided in the docs 我发现以下消息在日志中重复了很多次:

redux-persist asyncLocalStorage requires a global localStorage object. Either use a different storage backend or if this is a universal redux application you probably should conditionally persist like so: https://gist.github.com/rt2zz/ac9eb396793f95ff3c3b

我可以通过在创建 AppSync 客户端时关闭离线支持来解决这个问题,如下所示:

new AWSAppSyncClient({
  url: 'https://...appsync-api.us-west-2.amazonaws.com/graphql',
  region: 'us-west-2',
  auth: {
    type: 'AWS_IAM',
    credentials: ...
  },
  disableOffline: true
})

...不过我确实想使用线下商店。我正在使用文档中的设置配置,如下所示:

global.WebSocket = require('ws');
global.window = global.window || {
    setTimeout: setTimeout,
    clearTimeout: clearTimeout,
    WebSocket: global.WebSocket,
    ArrayBuffer: global.ArrayBuffer,
    addEventListener: function () { },
    navigator: { onLine: true }
};
global.localStorage = {
    store: {},
    getItem: function (key) {
        return this.store[key]
    },
    setItem: function (key, value) {
        this.store[key] = value
    },
    removeItem: function (key) {
        delete this.store[key]
    }
};
require('es6-promise').polyfill();
require('isomorphic-fetch');

但它似乎不适用于 redux-persist,它在 AppSync 客户端的深层使用。

我找到了一个非常简单的方法来解决这个问题。虽然这部分直接取自 AWS 文档,但并不完全正确:

global.localStorage = {
    store: {},
    ...
};

通过设置 global.window.localStorage 我可以解决以下问题:

global.window.localStorage = {
    store: {},
    ...
};

任何其他尝试像这样使用 AppSync 的人可能想知道 node-localstorage 似乎也适用于这种用法(在 yarn add node-localstorage 之后):

var LocalStorage = require('node-localstorage').LocalStorage
global.window.localStorage = new LocalStorage(<path for storage>)

重要的是,在这种情况下,您的查询会持久保存到文件系统中,并且在连接丢失时将被读取。这可能会在重新启动您的应用程序后起作用(但我尚未对此进行测试,因为您需要一个 AWS 凭证对象来创建 AppSync 客户端)。