bridge-node-server/node_server/utils/feature-flags/feature-flags.js
Martin Donnelly 57bd6c8e6a init
2018-06-24 21:15:03 +01:00

58 lines
2.0 KiB
JavaScript

/**
* Implements the functionality behind feature flags
*/
'use strict';
const flagsList = require('./flags-list.js');
const _ = require('lodash');
module.exports = {
flagsList: flagsList,
isEnabled: isEnabled
};
/**
* This function tests if the specified flag is enabled.
* At present, this is simply a check if the specified flag is in an array of
* featureFlags in the provided object.
* It can be expanded in the future to e.g. return true based on other params
* of the object such as email address, or randomly on ID.
*
* @param {String} flag - The flag to test for
* @param {Object} obj - The object to test if the flag is enabled
* @param {String[]} obj.FeatureFlags - Array of enabled flags for this obj
*
* @returns {boolean} - True if the feature is enabled
*
* @throws {Error} - Throws an Error if the flag is not in the declared
* list of valid flags as this likely indicates a typo
* in the code etc. Also throws if provided `obj` is
* not an object.
*/
function isEnabled(flag, obj) {
if (flagsList.indexOf(flag) === -1) {
throw new Error('Flag <' + flag + '> not declared. Check correct flag name in use.');
}
//
// Check that this is an object. Note that Arrays and Functions are also
// "objects" but not of the type we want.
//
if (!_.isObject(obj) || _.isArray(obj) || _.isFunction(obj)) {
throw new Error('Cannot test for flag as obj is not an object.');
}
if (!_.isUndefined(obj.FeatureFlags) && !_.isArray(obj.FeatureFlags)) {
throw new Error('obj.FeatureFlags must be undefined or an array.');
}
if (!_.isArray(obj.FeatureFlags)) {
return false; // No flags array is treated the same as flag no present
} else if (obj.FeatureFlags.indexOf(flag) === -1) {
return false; // Array of flags exists, but the flag isn't in it
} else {
return true; // Flag is in the list so the feature is enabled
}
}