ember-api-feature-flags

0.3.0 • Public • Published

ember-api-feature-flags Download count all time Build Status npm version Ember Observer Score

API based, read-only feature flags for Ember. To install:

ember install ember-api-feature-flags

How it works

ember-api-feature-flags installs a service into your app. This service will let you fetch your feature flag data from a specified URL.

For example, call fetchFeatures in your application route:

// application/route.js
import Ember from 'ember';
 
const { inject: { Service }, Route } = Ember;
 
export default Route.extend({
  featureFlags: service(),
 
  beforeModel() {
    this.get('featureFlags')
      .fetchFeatures()
      .then((data) => featureFlags.receiveData(data))
      .catch((reason) => featureFlags.receiveError(reason));
  }
});

Once fetched, you can then easily check if a given feature is enabled/disabled in both Handlebars:

{{#if featureFlags.myFeature.isEnabled}}
  <p>Do it</p>
{{/if}}
 
{{#if featureFlags.anotherFeature.isDisabled}}
  <p>Do something else</p>
{{/if}}

...and JavaScript:

import Ember from 'ember';
 
const {
  Component,
  inject: { service },
  get 
= Ember;
 
export default Component.extend({
  featureFlags: service(),
 
  actions: {
    save() {
      let isDisabled = get(this, 'featureFlags.myFeature.isDisabled');
 
      if (isDisabled) {
        return;
      }
 
      // stuff
    }
  }
});

API fetch failure

When the fetch fails, the service enters "error" mode. In this mode, feature flag lookups via HBS or JS will still function as normal. However, they will always return the default value set in the config (which defaults to false). You can set this to true if you want all features to be enabled in event of fetch failure.

Configuration

To configure, add to your config/environment.js:

/* eslint-env node */
module.exports = function(environment) {
  var ENV = {
    'ember-api-feature-flags': {
      featureUrl: 'https://www.example.com/api/v1/features',
      featureKey: 'feature_key',
      enabledKey: 'value',
      shouldMemoize: true,
      defaultValue: false
    }
  }
  return ENV;

featureUrl must be defined, or ember-api-feature-flags will not be able to fetch feature flag data from your API.

Fetching feature flags

Unauthenticated

For example, call fetchFeatures in your application route:

// application/route.js
import Ember from 'ember';
 
const { inject: { Service }, Route } = Ember;
 
export default Route.extend({
  featureFlags: service(),
 
  beforeModel() {
    this.get('featureFlags')
      .fetchFeatures()
      .then((data) => featureFlags.receiveData(data))
      .catch((reason) => featureFlags.receiveError(reason));
  }
});

Authenticated

In the following example, the application uses ember-simple-auth, and the authenticated data includes the user's email and token:

import Ember from 'ember';
import Session from 'ember-simple-auth/services/session';
 
const {
  inject: { service },
  get 
= Ember;
 
export default Session.extend({
  featureFlags: service(),
 
  // call this function after the session is authenticated
  fetchFeatureFlags() {
    let featureFlags = get(this, 'featureFlags');
    let { authenticated: { email, token } } = get(this, 'data');
    let headers = { Authorization: `Token token=${token}, email=${email}`};
    featureFlags
      .fetchFeatures({ headers })
      .then((data) => featureFlags.receiveData(data))
      .catch((reason) => featureFlags.receiveError(reason));
  }

featureUrl* {String}

Required. The URL where your API returns feature flag data. You can change this per environment in config/environment.js:

if (environment === 'canary') {
  ENV['ember-api-feature-flags'].featureUrl = 'https://www.example.com/api/v1/features';
}

featureKey {String} = 'feature_key'

This key is the key on your feature flag data object yielding the feature's name. In other words, this key's value determines what you will use to access your feature flag (e.g. this.get('featureFlags.newProfilePage.isEnabled')):

// example feature flag data object
{
  "id": 26,
  "feature_key": "new_profile_page", // <-
  "key": "boolean",
  "value": "true",
  "created_at": "2017-03-22T03:30:10.270Z",
  "updated_at": "2017-03-22T03:30:10.270Z"
}

The value on this key will be normalized by the normalizeKey method.

enabledKey {String} = 'value'

This determines which key to pick off of the feature flag data object. This value is then used by the FeatureFlag object (a wrapper around the single feature flag) when determining if a feature flag is enabled.

// example feature flag data object
{
  "id": 26,
  "feature_key": "new_profile_page",
  "key": "boolean",
  "value": "true", // <-
  "created_at": "2017-03-22T03:30:10.270Z",
  "updated_at": "2017-03-22T03:30:10.270Z"
}

shouldMemoize {Boolean} = true

By default, the service will instantiate and cache FeatureFlag objects. Set this to false to disable.

defaultValue {Boolean} = false

If the service is in error mode, all feature flag lookups will return this value as their isEnabled value.

API

didFetchData

Returns a boolean value that represents the success state of fetching data from your API. If the GET request fails, this will be false and the service will be set to "error" mode. In error mode, all feature flags will return the default value as the value for isEnabled.

⬆️ back to top

data

A computed property that represents the normalized feature flag data.

let data = service.get('data');
 
/**
  {
    "newProfilePage": { value: "true" },
    "newFriendList": { value: "true" }
  }
**/

⬆️ back to top

configure {Object}

Configure the service. You can use this method to change service options at runtime. Acceptable options are the same as in the configuration section.

service.configure({
  featureUrl: 'http://www.example.com/features',
  featureKey: 'feature_key',
  enabledKey: 'value',
  shouldMemoize: true,
  defaultValue: false
});

⬆️ back to top

fetchFeatures {Object} = options

Performs the GET request to the specified URL, with optional headers to be passed to ember-ajax. Returns a Promise.

service.fetchFeatures().then((data) => doStuff(data));
service.fetchFeatures({ headers: /* ... */}).then((data) => doStuff(data));

⬆️ back to top

receiveData {Object}

Receive data from API and set internal properties. If data is blank, we set the service in error mode.

service.receiveData([
  {
    "id": 26,
    "feature_key": "new_profile_page",
    "key": "boolean",
    "value": "true",
    "created_at": "2017-03-22T03:30:10.270Z",
    "updated_at": "2017-03-22T03:30:10.270Z"
  },
  {
    "id": 27,
    "feature_key": "new_friend_list",
    "key": "boolean",
    "value": "true",
    "created_at": "2017-03-22T03:30:10.287Z",
    "updated_at": "2017-03-22T03:30:10.287Z"
  }
]);
service.get('data') // normalized data

⬆️ back to top

receiveError {Object}

Set service in errored state. Records failure reason as a side effect.

service.receiveError('Something went wrong');
service.get('didFetchData', false);
service.get('error', 'Something went wrong');

⬆️ back to top

normalizeKey {String}

Normalizes keys. Defaults to camelCase.

service.normalizeKey('new_profile_page'); // "newProfilePage"

⬆️ back to top

get {String}

Fetches the feature flag. Use in conjunction with isEnabled or isDisabled on the feature flag.

service.get('newProfilePage.isEnabled'); // true
service.get('newFriendList.isEnabled'); // true
service.get('oldProfilePage.isDisabled'); // true

⬆️ back to top

setupForTesting

Sets the service in testing mode. This is useful when writing acceptance/integration tests in your application as you don't need to intercept the request to your API. When the service is in testing mode, all features are enabled.

service.setupForTesting();
service.get('newFriendList.isEnabled'); // true

⬆️ back to top

Installation

  • git clone <repository-url> this repository
  • cd ember-api-feature-flags
  • npm install
  • bower install

Running

Running Tests

  • npm test (Runs ember try:each to test your addon against multiple Ember versions)
  • ember test
  • ember test --server

Building

  • ember build

For more information on using ember-cli, visit https://ember-cli.com/.

Package Sidebar

Install

npm i ember-api-feature-flags

Weekly Downloads

1

Version

0.3.0

License

MIT

Last publish

Collaborators

  • mmun
  • sugarpirate