Skip to content

Commit

Permalink
feat: refactor the validation and query logic and optimize the naming
Browse files Browse the repository at this point in the history
  • Loading branch information
ChoGathK committed Aug 17, 2022
1 parent 01a3106 commit 5fcb217
Showing 1 changed file with 32 additions and 22 deletions.
54 changes: 32 additions & 22 deletions src/provider/config.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,68 @@
import { cloneDeep } from 'lodash';
import { Injectable } from '@nestjs/common';
import { This } from '@vodyani/class-decorator';
import { toDeepMerge, toDeepMatch, toDeepRestore, isValidDict, isKeyof } from '@vodyani/utils';
import { toDeepMerge, toDeepMatch, toDeepRestore, isValidObject, isKeyof } from '@vodyani/utils';
import { ArgumentValidator, CustomValidated, Required, This } from '@vodyani/class-decorator';

import { Dictionary } from '../common';

/**
* Configuration Accessor
*/
@Injectable()
export class ConfigProvider<T = any> {
/**
* The configuration details store.
*/
private store: Dictionary<T> = Object();

/**
* get the configuration for the given key.
* Get the configuration for the given key.
*
* @publicApi
*/
@This
public match(key: string) {
@ArgumentValidator()
public match(
@Required() key: string,
) {
const result = toDeepMatch(this.store, key);
return isValidDict(result) ? cloneDeep(result) as any : result;
return isValidObject(result) ? cloneDeep(result) as any : result;
}
/**
* get the configuration for the given key.
* Get the configuration for the given key.
*
* @tips Only the specified key can be queried, deep query is not supported.
*
* @usageNotes
* - Only the specified key can be queried, deep query is not supported
* @publicApi
*/
@This
public get<K extends keyof Dictionary<T>>(key: K) {
let result = null;
@ArgumentValidator()
public get<K extends keyof Dictionary<T>>(
@Required() key: K,
) {
if (isKeyof(this.store, key as string | number)) {
const result = this.store[key];

if (isKeyof(this.store, key as number | string)) {
result = this.store[key];
return isValidObject(result) ? cloneDeep(result) : result;
}

return isValidDict(result) ? cloneDeep(result) : result;
}
/**
* set the configuration for the given key.
*/
@This
public set(key: string, value: any): void {
@ArgumentValidator()
public set(
@Required() key: string,
@Required() value: any,
): void {
const result = toDeepRestore(value, key);
this.merge(result);
}
/**
* merge the configuration
*/
@This
public merge(value: object): void {
if (isValidDict(value)) {
this.store = toDeepMerge(this.store, cloneDeep(value));
}
@ArgumentValidator()
public merge(
@CustomValidated(isValidObject, 'value must be object !') value: object,
): void {
this.store = toDeepMerge(this.store, cloneDeep(value));
}
}

0 comments on commit 5fcb217

Please sign in to comment.