Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR to move away from @nestjs/config and integrate our own config service. #24

Merged
merged 4 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/cache/service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { IntentConfig } from '../config/service';
import { logTime } from '../utils/helpers';
import { InternalLogger } from '../utils/logger';
import { InMemoryDriver } from './drivers/inMemory';
import { RedisDriver } from './drivers/redis';
import { CacheDriver, CacheOptions } from './interfaces';
import { ConfigService } from '../config';

@Injectable()
export class CacheService implements OnModuleInit {
static driverMap = { redis: RedisDriver, memory: InMemoryDriver };
public static data: CacheOptions;
static stores: Record<string, CacheDriver>;

constructor(config: IntentConfig) {
CacheService.data = config.get('cache');
constructor(config: ConfigService) {
CacheService.data = config.get('cache') as CacheOptions;
}

onModuleInit() {
Expand Down
26 changes: 26 additions & 0 deletions lib/config/builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
NamespacedConfigMapKeys,
NamespacedConfigMapValues,
RegisterNamespaceReturnType,
} from './options';

export class ConfigBuilder {
static async build(
namespaceObjects: RegisterNamespaceReturnType<string, any>[],
): Promise<Map<string, any>> {
const configMap = new Map();

for (const namespacedConfig of namespaceObjects) {
const namespacedMap = new Map<
NamespacedConfigMapKeys,
NamespacedConfigMapValues
>();
namespacedMap.set('factory', namespacedConfig._.factory);
namespacedMap.set('static', await namespacedConfig._.factory());
namespacedMap.set('encrypt', namespacedConfig._.options.encrypt);
configMap.set(namespacedConfig._.namespace, namespacedMap);
}

return configMap;
}
}
53 changes: 26 additions & 27 deletions lib/config/command.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
import { Injectable } from '@nestjs/common';
import pc from 'picocolors';
import { Command, ConsoleIO } from '../console';
import { Obj } from '../utils';
import { Arr } from '../utils/array';
import { columnify } from '../utils/columnify';
import { IntentConfig } from './service';
import { ConfigMap } from './options';
import { CONFIG_FACTORY } from './constant';
import pc from 'picocolors';
import archy from 'archy';
import { Inject } from '../foundation';
import { jsonToArchy } from '../utils/console-helpers';

@Injectable()
@Command('config:view {--ns : Namespace of a particular config}', {
desc: 'Command to view config for a given namespace',
})
export class ViewConfigCommand {
constructor(private config: IntentConfig) {}
constructor(@Inject(CONFIG_FACTORY) private config: ConfigMap) {}

async handle(_cli: ConsoleIO): Promise<void> {
const nsFlag = _cli.option<string>('ns');
const printNsToConsole = (namespace, obj) => {
const values = obj.get('static') as Record<string, any>;
console.log(
archy(jsonToArchy(values, pc.bgGreen(pc.black(` ${namespace} `)))),
);
};

@Command('config:view {namespace}', {
desc: 'Command to view config for a given namespace',
})
async handle(_cli: ConsoleIO): Promise<boolean> {
const namespace = _cli.argument<string>('namespace');
const config = this.config.get(namespace);
if (!config) {
_cli.error(`config with ${namespace} namespace not found`);
if (nsFlag) {
const ns = this.config.get(nsFlag);
printNsToConsole(nsFlag, ns);
return;
}
const columnifiedConfig = columnify(
Arr.toObj(Obj.entries(config), ['key', 'value']),
);
const printRows = [];
for (const row of columnifiedConfig) {
printRows.push([pc.green(row[0]), pc.yellow(row[1])].join(' '));
}

// eslint-disable-next-line no-console
console.log(printRows.join('\n'));

return true;
// Example usage
for (const [namespace, obj] of this.config.entries()) {
printNsToConsole(namespace, obj);
}
}
}
1 change: 1 addition & 0 deletions lib/config/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const CONFIG_FACTORY = '@intentjs/config_factory';
6 changes: 6 additions & 0 deletions lib/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export * from './builder';
export * from './register-namespace';
export * from './options';
export * from './service';
export * from './command';
export * from './constant';
36 changes: 36 additions & 0 deletions lib/config/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export type RegisterNamespaceOptions = {
encrypt?: boolean;
};

export type BuildConfigFromNS<
T extends RegisterNamespaceReturnType<any, any>[],
> = {
[N in T[number]['_']['namespace']]: Extract<
T[number],
{ _: { namespace: N } }
>['$inferConfig'];
};

export type RegisterNamespaceReturnType<
N extends string,
T extends Record<string, any>,
> = {
_: {
namespace: N;
options: RegisterNamespaceOptions;
factory: () => T | Promise<T>;
};
$inferConfig: T;
};

export type NamespacedConfigMapKeys = 'factory' | 'static' | 'encrypt';

export type NamespacedConfigMapValues =
// eslint-disable-next-line @typescript-eslint/ban-types
Function | object | boolean | string | number;

export type NamespacedConfigMap = Map<
NamespacedConfigMapKeys,
NamespacedConfigMapValues
>;
export type ConfigMap = Map<string, NamespacedConfigMap>;
25 changes: 25 additions & 0 deletions lib/config/register-namespace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { LiteralString } from '../type-helpers';
import {
RegisterNamespaceOptions,
RegisterNamespaceReturnType,
} from './options';

// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();

export const registerNamespace = <N extends string, T>(
namespace: LiteralString<N>,
factory: () => T | Promise<T>,
options?: RegisterNamespaceOptions,
): RegisterNamespaceReturnType<LiteralString<N>, T> => {
return {
_: {
namespace,
options: {
encrypt: options?.encrypt ?? false,
},
factory,
},
$inferConfig: {} as T,
};
};
61 changes: 42 additions & 19 deletions lib/config/service.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,51 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Inject, Injectable } from '../foundation';
import { DotNotation, GetNestedPropertyType } from '../type-helpers';
import { Obj } from '../utils';
import { CONFIG_FACTORY } from './constant';
import { ConfigMap, NamespacedConfigMapValues } from './options';

type ConfigPaths<T> = DotNotation<T>;

@Injectable()
export class IntentConfig {
private static cachedConfig: Map<string, any>;
private static config: ConfigService;
export class ConfigService<G = undefined> {
private static cachedConfig = new Map<string, any>();
private static config: ConfigMap;

constructor(private config: ConfigService) {
IntentConfig.cachedConfig = new Map<string, any>();
IntentConfig.config = config;
constructor(@Inject(CONFIG_FACTORY) private config: ConfigMap) {
ConfigService.cachedConfig = new Map<ConfigPaths<G>, any>();
ConfigService.config = this.config;
}

get<T = any>(key: string): T {
if (IntentConfig.cachedConfig.has(key))
return IntentConfig.cachedConfig.get(key);
const value = this.config.get<T>(key);
IntentConfig.cachedConfig.set(key, value);
return value;
get<P extends string = ConfigPaths<G>, F = any>(
key: P,
): GetNestedPropertyType<G, P, F> | Promise<GetNestedPropertyType<G, P, F>> {
return ConfigService.get<G, P>(key);
}

static get<T = any>(key: string): T {
if (this.cachedConfig.has(key)) return this.cachedConfig.get(key);
const value = this.config.get<T>(key);
this.cachedConfig.set(key, value);
return value;
static get<C = undefined, P extends string = ConfigPaths<C>, F = any>(
key: P,
): GetNestedPropertyType<C, P, F> | Promise<GetNestedPropertyType<C, P, F>> {
const cachedValue = ConfigService.cachedConfig.get(key);
if (cachedValue) return cachedValue;

const [namespace, ...paths] = (key as string).split('.');
const nsConfig = this.config.get(namespace);
/**
* Returns a null value if the namespace doesn't exist.
*/
if (!nsConfig) return null;

if (!paths.length) return nsConfig.get('static') as any;

const staticValues = nsConfig.get('static') as Omit<
NamespacedConfigMapValues,
'function'
>;

const valueOnPath = Obj.get<any>(staticValues, paths.join('.'));
if (valueOnPath) {
this.cachedConfig.set(key as string, valueOnPath);
}
return valueOnPath;
}
}
4 changes: 2 additions & 2 deletions lib/database/service.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import Knex, { Knex as KnexType } from 'knex';
import { IntentConfig } from '../config/service';
import { logTime } from '../utils/helpers';
import { InternalLogger } from '../utils/logger';
import { BaseModel } from './baseModel';
import { ConnectionNotFound } from './exceptions';
import { DatabaseOptions, DbConnectionOptions } from './options';
import { ConfigService } from '../config';

@Injectable()
export class ObjectionService implements OnModuleInit {
static config: DatabaseOptions;
static dbConnections: Record<string, KnexType>;

constructor(config: IntentConfig) {
constructor(config: ConfigService) {
const dbConfig = config.get('db') as DatabaseOptions;
if (!dbConfig) return;
const defaultConnection = dbConfig.connections[dbConfig.default];
Expand Down
4 changes: 2 additions & 2 deletions lib/exceptions/intentExceptionFilter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ArgumentsHost, HttpException, Type } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { Log } from '../logger';
import { Request, Response } from '../rest/foundation';
import { Package } from '../utils';
Expand Down Expand Up @@ -29,7 +29,7 @@ export abstract class IntentExceptionFilter extends BaseExceptionFilter {
}

reportToSentry(exception: any): void {
const sentryConfig = IntentConfig.get('app.sentry');
const sentryConfig = ConfigService.get('app.sentry');
if (!sentryConfig?.dsn) return;

const exceptionConstructor = exception?.constructor;
Expand Down
3 changes: 1 addition & 2 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export * from './serializers/validationErrorSerializer';
export * from './mailer';
export * from './events';
export * from './validator';
export * from './config/service';
export * from './foundation';
export { registerAs } from '@nestjs/config';
export * from './reflections';
export * from './config';
6 changes: 3 additions & 3 deletions lib/localization/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { join } from 'path';
import { Injectable } from '@nestjs/common';
import { path } from 'app-root-path';
import { readdirSync, readFileSync } from 'fs-extra';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { Obj } from '../utils';
import { Num } from '../utils/number';
import { Str } from '../utils/string';
Expand All @@ -19,8 +19,8 @@ export class LocalizationService {
UNKNOWN: 0,
};

constructor(private config: IntentConfig) {
const options = config.get<LocalizationOptions>('localization');
constructor(private config: ConfigService) {
const options = config.get('localization') as LocalizationOptions;

const { path: dir, fallbackLang } = options;
const data: Record<string, any> = {};
Expand Down
6 changes: 3 additions & 3 deletions lib/logger/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { join } from 'path';
import { Injectable } from '@nestjs/common';
import { path } from 'app-root-path';
import * as winston from 'winston';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { Obj } from '../utils';
import { Num } from '../utils/number';
import {
Expand All @@ -21,8 +21,8 @@ export class LoggerService {
private static config: IntentLoggerOptions;
private static options: any = {};

constructor(private readonly config: IntentConfig) {
const options = this.config.get<IntentLoggerOptions>('logger');
constructor(private readonly config: ConfigService) {
const options = this.config.get('logger') as IntentLoggerOptions;
LoggerService.config = options;
for (const conn in options.loggers) {
LoggerService.options[conn] = LoggerService.createLogger(
Expand Down
4 changes: 2 additions & 2 deletions lib/mailer/message.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { render } from '@react-email/render';
// eslint-disable-next-line import/no-named-as-default
import IntentMailComponent from '../../resources/mail/emails';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { GENERIC_MAIL, RAW_MAIL, VIEW_BASED_MAIL } from './constants';
import {
MailData,
Expand Down Expand Up @@ -203,7 +203,7 @@ export class MailMessage {
if (this.compiledHtml) return this.compiledHtml;

if (this.mailType === GENERIC_MAIL) {
const templateConfig = IntentConfig.get('mailers.template');
const templateConfig = ConfigService.get('mailers.template');
const html = await render(
IntentMailComponent({
header: { value: { title: templateConfig.appName } },
Expand Down
4 changes: 2 additions & 2 deletions lib/mailer/service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@nestjs/common';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { logTime } from '../utils';
import { InternalLogger } from '../utils/logger';
import { MailData, MailerOptions } from './interfaces';
Expand All @@ -11,7 +11,7 @@ export class MailerService {
private static options: MailerOptions;
private static channels: Record<string, BaseProvider>;

constructor(private config: IntentConfig) {
constructor(private config: ConfigService) {
const options = this.config.get('mailers') as MailerOptions;

MailerService.options = options;
Expand Down
6 changes: 3 additions & 3 deletions lib/queue/metadata.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@nestjs/common';
import { IntentConfig } from '../config/service';
import { ConfigService } from '../config/service';
import { GenericFunction } from '../interfaces';
import { QueueOptions } from './interfaces';
import { JobOptions } from './strategy';
Expand All @@ -18,8 +18,8 @@ export class QueueMetadata {
>;
private static store: Record<string, any> = { jobs: {} };

constructor(private config: IntentConfig) {
const data = this.config.get<QueueOptions>('queue');
constructor(private config: ConfigService) {
const data = this.config.get('queue') as QueueOptions;
QueueMetadata.data = data;
QueueMetadata.defaultOptions = {
connection: data.default,
Expand Down
Loading
Loading