weaveworks / promjs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using localStorage to keep registry state when page reloaded

mrzacarias opened this issue · comments

Hi there,

Not a critical issue, but something that will be nice to have. Right now, whenever the user refresh the page, the registry state is lost forever. The way I'm doing now to solve this problem is quite brittle.

I store the JSON stringfied registry in the localStorage:

export function storePromRegistry() {
  localStorage.setItem("promjs_registry_json", JSON.stringify(promRegistry));
}

And then, whenever the registry is created, I check localStorage to see if there's any saved state there, loading it if so:

// Getting state from local storage
let promRegistryStored = localStorage.getItem("promjs_registry_json");
if (promRegistryStored) {
  let promRegistryDataJSON = JSON.parse(promRegistryStored);
  each(promRegistryDataJSON.data, (collectorGroup) => {
    each(collectorGroup, (collectorData, collectorName) => {
      let collector = promRegistry.get(collectorData.type, collectorName)
      if (collector && collectorData.instance.data[0]) (
        collector.set(collectorData.instance.data[0].value)
      )
    });
  });
}

Yep, it's an edge case and losing some metrics on refreshes is not the end of the world, but would be nice to have support from the lib for keeping the state if needed. 👍

@mrzacarias This would break our "isomorphic" goal, in that it would not be applicable in Node.js or another JavaScript environment. Of course we could probably check the environment and only write if in browser.

Saving state by default would not always be a desirable behavior. In our original use case, we wanted to track page load times, so resetting all of the metrics between refreshes was okay.

One way to generalize this would be to add the ability to de-serialize metrics from a string. That would keep things environment-agnostic.