ObjectSource
The ObjectSource implementation of ConfigurationSource is quite straightforward; it simply
uses a JavaScript Object as a source of configuration data. This is most useful for setting application
defaults or runtime overrides.
The default Configurator source list uses two ObjectSource implementations:
- A low-priority source reading from
context.defaults(sequence 300) - for application defaults - A high-priority source reading from
context.overrides(sequence 1000) - for runtime overrides
You can create additional ObjectSource instances with custom contextName values to read from different
fields in the context.
import { ObjectSource } from '@versionzero/configurator/sources';
// Custom source reading from context.magic
const magicSource = new ObjectSource({ contextName: 'magic', sequence: 500 });
const config = await Configurator.load(schema, {
sources: [
...Configurator.getDefaultSources(),
magicSource
],
magic: { server: { hostname: 'localhost' } }
});
caution
This library uses the word defaults in multiple contexts:
- Schema defaults (loaded by
SchemaDefaultsSource) - default values defined in schema - Application defaults (loaded by
ObjectSourcefromcontext.defaults) - application-level defaults
Constructor
new ObjectSource(options)
| Param | Type | Description |
|---|---|---|
[options] | object | Optional settings |
[options.sequence] | number | Priority number. Defaults to ConfigurationSource.DefaultSequence.APP_DEFAULTS (300) |
[options.contextName] | string | Name of context field to load from (default: "data") |
Examples
Basic Usage
import { ObjectSource } from '@versionzero/configurator/sources';
// Default contextName is 'data'
const source = new ObjectSource();
// Custom contextName
const defaultsSource = new ObjectSource({ contextName: 'defaults', sequence: 300 });
const overridesSource = new ObjectSource({ contextName: 'overrides', sequence: 1000 });
Complete Example
import { Schema, Configurator } from '@versionzero/configurator';
const schema = new Schema('object')
.property('host', new Schema('string'))
.property('port', new Schema('number'));
// Using the built-in defaults and overrides
const config = await Configurator.load(schema, {
defaults: { host: 'localhost', port: 3000 }, // Low priority (300)
overrides: { port: 8080 } // High priority (1000)
});
console.log(config); // { host: 'localhost', port: 8080 }