GithubHelp home page GithubHelp logo

pratikpparikh / ionic-configuration-service Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ritzlgrmft/ionic-configuration-service

0.0 2.0 0.0 79 KB

This service encapsulates configuration functionalities for apps built with Ionic framework.

JavaScript 13.71% TypeScript 86.16% HTML 0.07% CSS 0.05%
angular2 angular4 ionic2 ionic3 configuration-client

ionic-configuration-service's Introduction

ionic-configuration-service

The dependencies used by the latest version are the same as needed for Ionic 3.0.0. For older versions use:

  • Ionic 2.0.0: version 3.1.1.
  • Ionic 2.2.0: use version 4.0.0.

Build Codecov Version Downloads Dependencies Peer-Dependencies Dev-Dependencies Commitizen friendly Known Vulnerabilities License

This service encapsulates configuration functionalities for apps built with Ionic framework.

Most apps need some kind of configuration. And often, the configuration data is different between the environments:

  • maybe you want to use different web services in test and production
  • in test, you want to log everything, but in production only errors
  • you want to have all configuration data in one place, so you are able to change something easily
  • ...

The idea is:

  • add one json file containing all the configuration data
  • at build this file can be modified (par example you will use a different file in your release build)
  • before the app really starts, the configuration gets loaded
  • whereever you need the configuration data, you can get it via the injected configuration service

Settings file containing the configuration data

The settings file is just a JSON file. It contains some keys, whose values can be of any type (either scalar or complex):

{
  "helloWorld": "Hello World",
  "secretNumber": 42,
  "somethingComplex": {
    "backendUrl": "http://server.com/api"
  }
}

Replace settings file at build time

Now it gets a little bit tricky: you have a json file in a source directory (e.g. environments), which should be copied to the www/assets directory. A good place to do this is using the copy step of Ionic's build. You just need to add a copy statement to copy.config.js.

Unfortunately, the copied file should have always the same name. Otherwise you could not load it in your code. On the other side, you want to have several files (with different names) for the different environments. The solution is to have separate directories for every environment.

Folder structure

So, in the source, you have the following folder structure:

folder structure

Just create a new folder below environments for every environment you want to support. Be aware that the filename itself (settings.json) has to be always the same.

Copy correct environment

If you do not have an own copy.config.js, just create one. For details have a look at Custom configuration of Ionic's app scripts.

There you can add your own copy step to module.exports:

module.exports = {
  copySettings: {
    src: ['{{ROOT}}/environments/' + envDirectory + "/settings.json"],
    dest: '{{WWW}}/assets'
  },
  ...
}

As you can see, it simply copies the settings.json from envDirectory to www/assets. What is missing so far, is the right value of envDirectory, which has to be dynamic. Fortunately, copy.config.js is just JavaScript. So we can add some logic at the beginning:

var envDirectory = "default";
var envIndex = process.argv.indexOf("--env");
if (envIndex >= 0 && envIndex < process.argv.length - 1) {
  envDirectory = process.argv[envIndex + 1];
}

As you see, envDirectory has a default value of default. But if you call the build command with the --env argument, you can set there another environment. If you want to test the release environment in the emulator, you can use:

ionic emulate --prod --env release

Load the configuration data

The loading of the configuration data is done in the AppModule, before the bootstrapping of the IonicApp. This is done using Angular's APP_INITIALIZER:

import { APP_INITIALIZER } from "@angular/core";
import { ConfigurationService } from "ionic-configuration-service";

export function loadConfiguration(configurationService: ConfigurationService): () => Promise<void> {
  return () => configurationService.load("assets/settings.json");
}

@NgModule({
  ...
  providers: [
    ConfigurationService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfiguration,
      deps: [ConfigurationService],
      multi: true
    },
    ....
  ]
})

For APP_INITIALIZER, the factory function just loads the configuration data. The multi parameter is important, because there can be more APP_INITIALIZERs.

The factory function loadConfiguration() is needed, since otherwise the angular compiler ngc could not compile the module.

Access the configuration data

The access to the configuration data is quite easy. Just inject the ConfigurationService into your component. And call configurationService.getValue() later on:

constructor(
  private configurationService: ConfigurationService) {
}

let secretNumber = this.configurationService.getValue<number>("secretNumber");

For more complex configuration, it's a good practise to define an interface describing your part of the configuration:

export interface LoggingConfiguration {
  logLevels?: {
    loggerName: string;
    logLevel: string;
   }[];
}

let configuration = this.configurationService.getValue<LoggingConfiguration>("logging");

API

getKeys(): string[]

Get all available keys.

Returns

  • all available keys

getValue<T>(key: string): T

Get the configuration data for the given key.

Parameters

  • T: type of the returned value (default: object)
  • key: key of the configuration data

Returns

  • configuration data for the given key

load(configurationUrl: string): Promise<void>

Loads the configuration from the given url.

Parameters

  • configurationUrl url from which the configuration should be loaded

Returns

  • promise which gets resolved as soon as the data is loaded; in case of an error, the promise gets rejected

ionic-configuration-service's People

Contributors

pratikpparikh avatar ritzlgrmft avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.