Skip to content

Commit

Permalink
feat: add config changes stream
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Feb 7, 2024
1 parent 78cd4f2 commit 1af2431
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 301 deletions.
18 changes: 18 additions & 0 deletions lib/config.service.ts
Expand Up @@ -5,10 +5,12 @@ import fs from 'fs';
import get from 'lodash/get';
import has from 'lodash/has';
import set from 'lodash/set';
import { Subject } from 'rxjs';
import {
CONFIGURATION_TOKEN,
VALIDATED_ENV_PROPNAME,
} from './config.constants';
import { ConfigChangeEvent } from './interfaces/config-change-event.interface';
import { NoInferType, Path, PathValue } from './types';

/**
Expand Down Expand Up @@ -53,6 +55,7 @@ export class ConfigService<
}

private readonly cache: Partial<K> = {} as any;
private readonly _changes$ = new Subject<ConfigChangeEvent>();
private _isCacheEnabled = false;
private envFilePaths: string[] = [];

Expand All @@ -62,6 +65,14 @@ export class ConfigService<
private readonly internalConfig: Record<string, any> = {},
) {}

/**
* Returns a stream of configuration changes.
* Each event contains the attribute path, the old value and the new value.
*/
get changes$() {
return this._changes$.asObservable();
}

/**
* Get a configuration value (either custom configuration or process environment variable)
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
Expand Down Expand Up @@ -208,6 +219,7 @@ export class ConfigService<
* @param value
*/
set<T = any>(propertyPath: KeyOf<K>, value: T): void {
const oldValue = this.get(propertyPath);
set(this.internalConfig, propertyPath, value);

if (typeof propertyPath === 'string') {
Expand All @@ -218,6 +230,12 @@ export class ConfigService<
if (this.isCacheEnabled) {
this.setInCacheIfDefined(propertyPath, value);
}

this._changes$.next({
path: propertyPath as string,
oldValue,
newValue: value,
});
}
/**
* Sets env file paths from `config.module.ts` to parse.
Expand Down
10 changes: 10 additions & 0 deletions lib/interfaces/config-change-event.interface.ts
@@ -0,0 +1,10 @@
/**
* Represents a change in the configuration object.
* Dispatched when one updates the configuration object through the `ConfigService#set` method.
* @publicApi
*/
export interface ConfigChangeEvent<OldValue = any, NewValue = any> {
path: string;
oldValue: OldValue;
newValue: NewValue;
}
1 change: 1 addition & 0 deletions lib/interfaces/index.ts
@@ -1,2 +1,3 @@
export * from './config-change-event.interface';
export * from './config-factory.interface';
export * from './config-module-options.interface';

0 comments on commit 1af2431

Please sign in to comment.