Configuration class
import Configuration from '@bbc/front-end-kit/js/managers/Configuration';
A class for managing configuration settings in web applications.
Introduction
The Configuration class is a JavaScript class designed for managing configuration settings in web applications. It uses lodash library for efficient data manipulation and EventDispatcher class for handling custom events.
Getting Started
Once you have imported the Configuration class, you can create an instance of it by passing the required parameters. Here's an example:
const config = new Configuration({
config: { // config object
someValue: 'Hello World!'
},
defaultConfig: { // default configuration object
someValue: 'Default Value'
},
autoUpdate: true, // automatically update when configuration is changed
autoPrefill: true // automatically prefill configuration values on DOM load
});
You can now use the Configuration class to get, set, clear, or reset configuration settings.
// get configuration value
const someValue = config.get('someValue');
// set configuration value
config.set('someValue', 'New Value');
// clear configuration value
config.clear('someValue');
// reset configuration value
config.reset('someValue');
API Documentation
constructor(args)
Creates a new Configuration instance.
Parameters
args(object): An object containing the following properties:config(object): A configuration object to use as the default configuration.defaultConfig(Configuration): A Configuration instance to use as the default configuration. This will take precedence overdefaultConfigUrl.defaultConfigUrl(string): A URL to fetch the default configuration from. This will only be used ifdefaultConfigis not specified.autoFetch(boolean): Iftrue, the default configuration will be automatically fetched from the specified URL. Default isfalse.autoUpdate(boolean): Iftrue, the configuration will automatically update itself when the default configuration changes. Default isfalse.autoPrefill(boolean): Iftrue, the configuration will automatically prefill all fields with their default values. Default isfalse.dataAttrLabels(object): An object containing the labels to use for the data attributes. The default values are{ path: 'c-path', bind: 'c-bind', valueOverride: 'c-value-override', valueToAttr: 'c-value-to-attr' }._pathPlaceholderOpenSymbol(string): The symbol used to open path placeholders. Default:{{. Note: the leading underscore on this arg name is unusual — it is the literal key the constructor reads fromargs._pathPlaceholderCloseSymbol(string): The symbol used to close path placeholders. Default:}}. Same naming caveat as above.pathPlaceholders(object): An object containing the placeholders to use in paths.
Methods
get(path)
Gets the value at the specified path.
Parameters
path(string): The path to get the value from.
Returns
- The value at the specified path.
getDefault(path)
Gets the default value at the specified path.
Parameters
path(string): The path to get the default value from.
Returns
- The default value at the specified path.
set(path, value)
Sets the value at the specified path.
Parameters
path(string): The path to set the value at.value(any): The value to set.
Returns
- The Configuration instance, to allow chaining.
clear(path)
Clears the value at the specified path.
Parameters
path(string): The path to clear the value at.
Returns
- The Configuration instance, to allow chaining.
reset(path)
Resets the value at the specified path to the default value.
Parameters
path(string): The path to reset the value at.
Returns
- The Configuration instance, to allow chaining.
has(path)
Returns true if the value at the given path is truthy, false otherwise.
Parameters
path(string): The path to check.
Returns
Boolean.
isDefault(path)
Compares the current value at path with the default config value using lodash eq. Returns null if no default config is set.
Parameters
path(string): The path to check.
Returns
Boolean or null.
async fetchDefault({ urlOverride, fetchOptions })
Fetches default config JSON from defaultConfigUrl (or urlOverride). On success, replaces _defaultConfig and clones it into _config, then calls prefill() if autoPrefill is set. Dispatches default-loaded. On non-200 status, logs a warning and resolves silently.
Parameters
urlOverride(string, optional): Overrides thedefaultConfigUrlset during construction.fetchOptions(object, optional): Options forwarded to the nativefetch()call.
Returns
Promise<Response> on success, or a resolved Promise<void> on failure.
prefill(paths = null)
Scans the DOM for elements with the data-c-path attribute and fills them with the current config value at that path. If paths is provided, only elements matching those paths are updated.
Parameters
paths(string | string[] | null): One or more config paths to target.nullupdates alldata-c-pathelements.
Returns
The Configuration instance (chainable).
parsePath({ $field, tag, type, path, origin })
Hook called before every path lookup. If path contains {{...}} placeholder syntax it replaces them using _pathPlaceholders. Override in a subclass to add custom path transforms.
Returns
Resolved path string.
parseValue({ $field, tag, type, path, value, origin })
Hook called after every value lookup. Base implementation returns value as-is. Override in a subclass to coerce or transform values.
Returns
The (possibly transformed) value.
parseData(data)
Hook called on the raw JSON response from fetchDefault. Base implementation returns data as-is. Override to reshape the fetched payload before it is stored.
Returns
The (possibly transformed) data object.
initAutoUpdate()
Scans the DOM for [data-c-bind] elements and attaches input/click listeners that call set() on change. Called automatically during construction when autoUpdate is true.
Returns
The Configuration instance (chainable).
clone(deep = false)
Returns a new Configuration instance from the current one. If deep is true, config and defaultConfig are deep-cloned to prevent shared mutations.
Parameters
deep(boolean, defaultfalse): Whether to deep-clone the config objects.
Returns
A new Configuration instance.
toString()
Returns '[object Configuration]'.
Events
get
Dispatched on every get() call. e.detail: { path, value, rawValue }.
getDefault
Dispatched on every getDefault() call. e.detail: { path, value, rawValue }.
set
Dispatched on every set() and reset() call. e.detail: { path, rawValue, value }. On reset() also includes oldValue and oldRawValue.
clear
Dispatched on every clear() call. e.detail: { path }.
default-loaded
Dispatched after a successful fetchDefault(). e.detail: { url, response, fetchOptions }.
Getters and Setters
config
The current configuration object.
defaultConfig
The default configuration object, or null if none is set.
dictionary
A flat dot-notation dictionary of the current config, generated via createObjectDict. Useful for enumerating all paths.
pathPlaceholders
The current set of path placeholder key-value pairs used by parsePath.
Private properties
_config
The object representing the current configuration settings
_defaultConfig
The object representing the default config
_defaultConfigUrl
The url that is used to fetch the default configuration settings
_autoUpdate
Flag to activate automatic updates of the configuration when values change
_autoPrefill
Flag to automatically prefill DOM elements with configuration values.
_dataAttrLabels
Contains custom data attribute labels used for path, bind, valueOverride, and valueAttr
_pathPlaceholderOpenSymbol
String representing the opening symbol for path placeholders.
_pathPlaceholderCloseSymbol
String representing the closing symbol for path placeholders.
_pathPlaceholders
The object containing key-value pairs of the placeholders it needs to look for in paths
Dependencies
This class uses the following external dependencies:
- lodash: For some quick and usefull utility methods like:
- eq: Performs a SameValueZero comparison between two values to determine if they are equivalent.
- get: Gets a property out of a multi-level object using a string as path
- set: Sets a value to a property inside of a multi-level object using a string as path
- unset: Removes a property out of a multi-level object using a string as path
- camelCase: Transforms a string to camelCase
- cloneDeep: Clones an object recusively
- defaults: Provides default values a for an object (top level only)
Tips & Tricks
- Make use of the
autoUpdateoption to automatically fetch the default configuration on a specified interval and update the configuration with any changes made. - Use the
autoPrefilloption to automatically prefill any elements with a matchingdata-c-pathattribute when thedefaultConfigor configuration is updated. - Use the
data-c-pathanddata-c-value-to-attrattributes to easily bind configuration values to HTML elements without the need for additional scripting.