Set a dynamic configuration object in the app by reading it from the server

Set a dynamic configuration object in the app by reading it from the server


What we are going to achieve is:

  1.  Having just one place (the server!) where to set some config parameters. (Those are useful for both server and client)
  2. If later we decide to change a parameter like the size limit of file uploading, we will just change it in the server, we will not have to change the app avoiding rebuildings, and the need of resubmitting it in the stores.
  3. The app keeps the config object in the local storage to avoid extra api calls, but refreshes it every time it starts.

First of all in the server I have a config file like:

I set AppConfig just with the values I want to share with the client app (I don’t want to share the whole configuration)

Add a route in koa like:

config_ctl looks like:

When I call my endpoint I get a Json string like:

Perfect, let’s move on the app.

First of all I create a new provider by using ionic-cli:

let’s edit /src/providers/config.ts

 

Things to notice:

  • Storage is a confortable interface to the SQLite db built-in all moder browsers (it has fallback, check http://ionicframework.com/docs/storage/)
  • I created a service to interact with my api, but you can use http directly.
  • I use async/await, no worries it is just like a Promise.

That the first time the service is used, the api call result is saved in the storage, all the next calls are resolved internally by reading the local storage and no further calls are performed.

The last thing we need to do is to refresh the storage when the app restarts.

we just insert in /src/app/app.component.ts

Now we can inject the service where we need to have the config parameters available.

For instance, In a custom validator of mine, I used the config service in this way:

That’s all!

Leave a Reply

Your email address will not be published. Required fields are marked *