Refresh your JavaScript configurations with freshen-up

Today I wrote a simple (silly, I’d say) library that I had in mind since a while to refresh configuration values for JS apps.

The library is called freshen-up and it comes from some internal discussions we had at Namshi on how to refresh some content we load once a NodeJS app boots.

I was discussing various approaches with Lucio and, even if we don’t need to employ anything like this at the moment, I decided to give it a shot to see how simple it would have been to write down something that would do that.

Turns out there are a few different approaches to do this:

I then decided to give a try to the third approach and released freshen-up; it’s usage is pretty straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
var freshenUp = require('freshen-up');

function loadConfigurationFromTheDatabase() {
  // ...do stuff...
};

var config = freshenUp(loadConfigurationFromTheDatabase);

config.get().someValue; // will be something

// after some time...

config.get().someValue; // will be something else

The library will refresh the configuration, by default, every 50ms, though you can override this:

1
2
3
4
5
6
7
8
9
10
// Refreshing the configuration every 1s
var config = freshenUp(loadConfigurationFromTheDatabase, 1000);

config.get().someValue; // will be "something"

// after 500ms
config.get().someValue; // will still be "something"

// after 1s
config.get().someValue; // will be "something else"

freshen-up is basically just a nice wrapper over the JavaScript’s global setInterval function, so nothing really fancy here.

By the way, you can also use freshen-up to do other things like running checks every N seconds:

1
2
3
4
5
6
7
8
9
function checkIfInternetIsDown() {
  require('dns').resolve('www.google.com', function(err) {
    if (err) {
      doSomethingDude(err);
    }
  });
};

freshenUp(checkIfInternetIsDown, 1000);

That’s basically it: I added a couple tests just in case, though I still think there are better ways to do cache invalidation.


In the mood for some more reading?

...or check the archives.