macbutch
macbutch

Reputation: 3291

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

Following the example provided in the docs I find the following message repeated many times in the logs:

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

I can work around it by turning off offline support when creating the AppSync client, like this:

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

... however I do want to use the offline store. I am using the setup config from the documentation like so:

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');

But it doesn't seem to work with redux-persist which is used a few layers deep in the AppSync client.

Upvotes: 2

Views: 330

Answers (1)

macbutch
macbutch

Reputation: 3291

I have found a very simple way to resolve this issue. While this section is taken directly from the AWS docs it is not quite right:

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

By setting global.window.localStorage instead I am able to work around the issues:

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

Anyone else trying to use AppSync like this may want to know that node-localstorage also seems to work with this usage (after yarn add node-localstorage):

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

Importantly, in this case, your queries are persisted to the file system and will be read if connectivity is lost. This could potentially work after restarting your application (but I've not tested this yet because you need an AWS credentials object to create the AppSync client).

Upvotes: 2

Related Questions