Json Business values from server side to client side

39 views Asked by At

I have several business values such as date ranges, prices ranges, coeficients, etc. I don't want hard code this values so I thought return to the client side from server side a JSON with all of these values so I have some questions.

  1. Is this a good approach? if yes, how can I the Json business values global in order to access to the data from anywhere?
  2. If is not a good approach, what strategy you suggest?
1

There are 1 answers

0
Jordan Running On BEST ANSWER

Sure, it's a fine approach, although there's not much advantage of using JSON (a data serialization format that happens to be a subset of JavaScript) over using plain old JavaScript.

How you do it depends a lot on your current architecture. In the very simplest case, you could just inject it into your HTML before any of your other JavaScript is loaded:

<script>
window.AppConfiguration = {
  businessRules: {
    dateRanges: // ...
  }
};
</script>

...then in your other scripts you can access window.AppConfiguration to get your configuration values.

If you're already using something like RequireJS or Browserify, though, you might create a module instead:

// app/configuration.js
// RequireJS style
define({
  businessRules: { ... }
});

// Node.js/Browserify style
module.exports = {
  businessRules: { ... }
}

Then you can just do var appConfig = require('app/configuration'); and be on your way. This also has advantages with regard to testing and build tools.