Skip to content

Commit

Permalink
refactor: enable strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Papooch committed Oct 5, 2022
1 parent ae5f6d9 commit ea9b386
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 53 deletions.
6 changes: 4 additions & 2 deletions src/lib/cls.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import { ClsGuardOptions } from './cls.interfaces';

@Injectable()
export class ClsGuard implements CanActivate {
private readonly options: Omit<ClsGuardOptions, 'mount'>;

constructor(
@Inject(CLS_GUARD_OPTIONS)
private readonly options?: ClsGuardOptions,
options: Omit<ClsGuardOptions, 'mount'>,
) {
this.options = { ...new ClsGuardOptions(), ...options };
}
Expand All @@ -22,7 +24,7 @@ export class ClsGuard implements CanActivate {
return cls.exit(async () => {
cls.enter();
if (this.options.generateId) {
const id = await this.options.idGenerator(context);
const id = await this.options.idGenerator?.(context);
cls.set<any>(CLS_ID, id);
}
if (this.options.setup) {
Expand Down
6 changes: 4 additions & 2 deletions src/lib/cls.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import { ClsInterceptorOptions } from './cls.interfaces';

@Injectable()
export class ClsInterceptor implements NestInterceptor {
private readonly options: Omit<ClsInterceptorOptions, 'mount'>;

constructor(
@Inject(CLS_INTERCEPTOR_OPTIONS)
private readonly options?: Omit<ClsInterceptorOptions, 'mount'>,
options?: Omit<ClsInterceptorOptions, 'mount'>,
) {
this.options = { ...new ClsInterceptorOptions(), ...options };
}
Expand All @@ -24,7 +26,7 @@ export class ClsInterceptor implements NestInterceptor {
return new Observable((subscriber) => {
cls.run(async () => {
if (this.options.generateId) {
const id = await this.options.idGenerator(context);
const id = await this.options.idGenerator?.(context);
cls.set<any>(CLS_ID, id);
}
if (this.options.setup) {
Expand Down
14 changes: 7 additions & 7 deletions src/lib/cls.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ export class ClsModuleOptions {
/**
* An object with additional options for the `ClsMiddleware`
*/
middleware?: ClsMiddlewareOptions = null;
middleware?: ClsMiddlewareOptions;

/**
* An object with additional options for the `ClsGuard`
*/
guard?: ClsGuardOptions = null;
guard?: ClsGuardOptions;

/**
* An object with additional options for the `ClsInterceptor`
*/
interceptor?: ClsInterceptorOptions = null;
interceptor?: ClsInterceptorOptions;

/**
*
* Array of Proxy Provider classes to register
*/
proxyProviders?: Type[];
}
Expand All @@ -35,7 +35,7 @@ export type ClsModuleFactoryOptions = Omit<
>;
export interface ClsModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
inject?: any[];
useFactory?: (
useFactory: (
...args: any[]
) => Promise<ClsModuleFactoryOptions> | ClsModuleFactoryOptions;
/**
Expand All @@ -45,9 +45,9 @@ export interface ClsModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
global?: boolean;

/**
*
* Array of Proxy Provider classes to register
*/
providers?: Type[];
proxyProviders?: Type[];
}

export class ClsMiddlewareOptions {
Expand Down
5 changes: 3 additions & 2 deletions src/lib/cls.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ import { ClsService } from './cls.service';
@Injectable()
export class ClsMiddleware implements NestMiddleware {
private readonly cls: ClsService;
private readonly options: Omit<ClsMiddlewareOptions, 'mount'>;

constructor(
@Inject(CLS_MIDDLEWARE_OPTIONS)
private readonly options?: Omit<ClsMiddlewareOptions, 'mount'>,
options?: Omit<ClsMiddlewareOptions, 'mount'>,
) {
this.options = { ...new ClsMiddlewareOptions(), ...options };
}
Expand All @@ -24,7 +25,7 @@ export class ClsMiddleware implements NestMiddleware {
const callback = async () => {
this.options.useEnterWith && cls.enter();
if (this.options.generateId) {
const id = await this.options.idGenerator(req);
const id = await this.options.idGenerator?.(req);
cls.set<any>(CLS_ID, id);
}
if (this.options.saveReq) cls.set<any>(CLS_REQ, req);
Expand Down
37 changes: 23 additions & 14 deletions src/lib/cls.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,9 @@ export class ClsModule implements NestModule {
static forRoot(options?: ClsModuleOptions): DynamicModule {
options = { ...new ClsModuleOptions(), ...options };
const { providers, exports } = this.getProviders();
const proxyProviders =
options.proxyProviders?.map((providerClass) =>
ProxyProviderManager.createProxyProvider({
useClass: providerClass,
}),
) ?? [];
const proxyProviders = this.createProxyClassProviders(
options.proxyProviders,
);

return {
module: ClsModule,
Expand All @@ -112,6 +109,9 @@ export class ClsModule implements NestModule {

static forRootAsync(asyncOptions: ClsModuleAsyncOptions): DynamicModule {
const { providers, exports } = this.getProviders();
const proxyProviders = this.createProxyClassProviders(
asyncOptions.proxyProviders,
);

return {
module: ClsModule,
Expand All @@ -123,8 +123,9 @@ export class ClsModule implements NestModule {
useFactory: asyncOptions.useFactory,
},
...providers,
...proxyProviders,
],
exports,
exports: [...exports, ...proxyProviders.map((p) => p.provide)],
global: asyncOptions.global,
};
}
Expand All @@ -133,14 +134,10 @@ export class ClsModule implements NestModule {
* Registers the `ClsService` provider in the module
*/
static forFeature(): DynamicModule;
static forFeature(...requestScopedProviders: Array<Type>): DynamicModule;
static forFeature(...requestScopedProviders: Array<Type>): DynamicModule {
static forFeature(...proxyProviderClasses: Array<Type>): DynamicModule;
static forFeature(...proxyProviderClasses: Array<Type>): DynamicModule {
const proxyProviders =
requestScopedProviders.map((providerClass) =>
ProxyProviderManager.createProxyProvider({
useClass: providerClass,
}),
) ?? [];
this.createProxyClassProviders(proxyProviderClasses);
const providers = [...commonProviders];
return {
module: ClsModule,
Expand All @@ -165,6 +162,18 @@ export class ClsModule implements NestModule {
};
}

private static createProxyClassProviders(
proxyProviderClasses?: Array<Type>,
) {
return (
proxyProviderClasses?.map((providerClass) =>
ProxyProviderManager.createProxyProvider({
useClass: providerClass,
}),
) ?? []
);
}

private static getProviders() {
const providers: Provider[] = [
...commonProviders,
Expand Down
4 changes: 3 additions & 1 deletion src/lib/proxy-provider/proxy-provider-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ export class ProxyProviderManager {
}

private static async resolveProxyProvider(providerSymbol: symbol) {
const provider = this.proxyProviderMap.get(providerSymbol);
const provider = this.proxyProviderMap.get(
providerSymbol,
) as ProxyProvider;
if (isProxyClassProvider(provider)) {
await this.resolveProxyClassProvider(providerSymbol, provider);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/proxy-provider/proxy-provider.exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class UnknownProxyDependenciesException extends Error {
// matches the parameters from NestJS's error message:
// e.g: "Nest can't resolve dependencies of the Something (Cats, ?). [...]"
// returns ['Cats', '?']
return error.message.match(/\w+ \((.*?)\)./)[1].split(', ');
return error.message.match(/\w+ \((.*?)\)./)?.[1].split(', ') ?? [];
}

private static composeMessage(
Expand Down
2 changes: 1 addition & 1 deletion src/utils/value-from-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {

export function getValueFromPath<T, TP extends RecursiveKeyOf<T> & string>(
obj: T,
path?: TP,
path: TP,
): DeepPropertyType<T, TP> {
const pathSegments = path.split('.');
return pathSegments.reduce((acc, curr) => acc?.[curr], obj);
Expand Down
2 changes: 1 addition & 1 deletion test/proxy-providers/for-feature.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function createAndInitTestingApp(imports: ModuleMetadata['imports']) {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
ClsModule.forRoot({ middleware: { mount: true } }),
...imports,
...(imports ?? []),
],
}).compile();
const app = moduleFixture.createNestApplication();
Expand Down
44 changes: 22 additions & 22 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"rootDir": ".",
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
},
"include": ["src/**/*.ts", "test/**/*.ts"]
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"rootDir": ".",
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}

0 comments on commit ea9b386

Please sign in to comment.