Decoupling data storage / retrieval

This is more a general question than specific to js, but I’m posting it here since it relates to a js object I’m working on. I have an object that tries to fetch its data from localStorage. If it’s not available or the fetched data is no longer valid, then it fetches fresh data via an AJAX request, and stores the fresh data in localStorage.

I’d like to decouple this behaviour from the object, however I’ve got a bit stuck. I’ve created a separate ‘dataStore’ object and moved the localStorage and AJAX logic into there. Then this can be passed into the object, which can just call the dataStore’s ‘getData’ method to fetch the data, without caring where the data comes from.

The problem comes with validating the data retrieved from localStorage. One solution would be that the object passes a validation callback to the dataStore. The dataStore can then use this to check whether the data from localStorage is valid or whether fresh data needs to be fetched from the server. But I’m not sure this makes sense - if you were using the script on a server and using a database for the dataStore object, it shouldn’t need any validation callback.

Another option would be to allow registration of multiple dataStores on the object. The object calls the getData method of the first registered dataStore, then validates the returned data. If validation fails it moves on to the second registered dataStore, and so on. When it gets back valid data, it calls the storeData method of all previously tried dataStore objects that returned invalid data to update them with the valid data.

So rather than a single dataStore that uses localStorage and AJAX, I’d have separate localStorage and AJAX dataStores, registering the localStorage one with my object first, then registering the AJAX one as the second dataStore it should use. I think this is probably my preferred option.

The last option I can think of would be that I have cachedDataStore (localStorage) and freshDataStore (AJAX) that are passed into the object. The object first gets the data from the cachedDataStore. It validates the data, and if it is invalid it then gets the data from the freshDataStore, and then updates the cachedDataStore. The benefit of this is that we only do the validation where it is needed - for the cached data. But I’m not sure I really like treating cached data differently. I don’t think the object should be concerned with whether the data is from cache or not, it should just be concerned with getting valid data.

Does anyone else have any opinions or suggestions on this?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.