From 8525d9b0a474e5b55bb3aeaa124d710b587ff364 Mon Sep 17 00:00:00 2001 From: Rubin Bhandari Date: Mon, 14 Aug 2023 21:41:39 +0545 Subject: [PATCH] fix: lint --- src/common/@types/global.d.ts | 3 ++ src/common/decorators/user.decorator.ts | 4 +-- .../validation/is-date-format.validator.ts | 6 ++-- .../validation/is-greater-than.validator.ts | 2 +- .../validation/is-unique.validator.spec.ts | 6 ++-- .../validation/is-unique.validator.ts | 4 +-- .../validation/transform.decorator.ts | 33 ++++++++++--------- src/common/guards/jwt.guard.ts | 2 +- src/common/guards/throttle.guard.ts | 3 +- src/common/guards/ws.guard.ts | 2 +- .../interceptors/app-exit.interceptor.ts | 2 +- src/common/interceptors/logger.interceptor.ts | 14 ++++---- src/lib/casl/policies.guard.ts | 4 +-- src/lib/pino/pino.module.ts | 2 +- src/modules/auth/auth.service.ts | 2 +- 15 files changed, 47 insertions(+), 42 deletions(-) diff --git a/src/common/@types/global.d.ts b/src/common/@types/global.d.ts index b3ff1085..61f03022 100644 --- a/src/common/@types/global.d.ts +++ b/src/common/@types/global.d.ts @@ -9,6 +9,9 @@ namespace Express { export interface Request { user?: UserEntity; realIp: string; +body : Record; +ip: string; +ips: string[]; } } diff --git a/src/common/decorators/user.decorator.ts b/src/common/decorators/user.decorator.ts index 92acd59a..f23ce4f2 100644 --- a/src/common/decorators/user.decorator.ts +++ b/src/common/decorators/user.decorator.ts @@ -9,7 +9,7 @@ export const LoggedInUser = createParamDecorator((data: keyof User, context: Exe if (context.getType() === 'ws') request = context.switchToWs().getClient().handshake; - const user = request.user; + const user: User = request.user; - return data ? user?.[data] : user; + return data ? user[data] : user; }); diff --git a/src/common/decorators/validation/is-date-format.validator.ts b/src/common/decorators/validation/is-date-format.validator.ts index 740dfc0c..882e4a62 100644 --- a/src/common/decorators/validation/is-date-format.validator.ts +++ b/src/common/decorators/validation/is-date-format.validator.ts @@ -8,16 +8,16 @@ import { registerDecorator, } from 'class-validator'; import { isMatch } from 'date-fns'; -import { HelperService } from '@common/helpers'; +import { isArray } from 'helper-fns'; /* It validates that a date is in a given format */ @ValidatorConstraint({ async: true }) class IsDateInFormatConstraint implements ValidatorConstraintInterface { async validate(value: string | string[], arguments_: ValidationArguments) { - const [format] = arguments_.constraints; + const [format] = arguments_.constraints as string[]; - if (HelperService.isArray(value)) + if (isArray(value)) return value.some(v => isMatch(v, format)); return isMatch(value, format); diff --git a/src/common/decorators/validation/is-greater-than.validator.ts b/src/common/decorators/validation/is-greater-than.validator.ts index c45258b6..517464ee 100644 --- a/src/common/decorators/validation/is-greater-than.validator.ts +++ b/src/common/decorators/validation/is-greater-than.validator.ts @@ -12,7 +12,7 @@ import { class IsGreaterThanConstraint implements ValidatorConstraintInterface { async validate(value: string, arguments_: ValidationArguments) { const [relatedPropertyName] = arguments_.constraints; - const relatedValue = (arguments_.object as any)[relatedPropertyName]; + const relatedValue: string = (arguments_.object as any)[relatedPropertyName]; return Number.parseFloat(value) > Number.parseFloat(relatedValue); } diff --git a/src/common/decorators/validation/is-unique.validator.spec.ts b/src/common/decorators/validation/is-unique.validator.spec.ts index 2ebdd07e..17cb66f8 100644 --- a/src/common/decorators/validation/is-unique.validator.spec.ts +++ b/src/common/decorators/validation/is-unique.validator.spec.ts @@ -11,7 +11,7 @@ describe('IsUnique', () => { const mockEm = createMock(); const username = 'tester'; - const arguments_: IsUniqueValidationContext = { + const validatorArguments: IsUniqueValidationContext = { object: { username }, constraints: [() => User, 'username' as never], value: username, @@ -29,7 +29,7 @@ describe('IsUnique', () => { it('should pass if there are no duplicates', async () => { mockEm.count.mockResolvedValue(0); - const result = await isUnique.validate(username, arguments_); + const result = await isUnique.validate(username, validatorArguments); expect(result).toBeTruthy(); expect(mockEm.count).toBeCalledWith(User, { username }); @@ -37,7 +37,7 @@ describe('IsUnique', () => { it('should fail if there are duplicates', async () => { mockEm.count.mockResolvedValue(1); - const result = await isUnique.validate(username, arguments_); + const result = await isUnique.validate(username, validatorArguments); expect(result).toBeFalsy(); expect(mockEm.count).toBeCalledWith(User, { username }); diff --git a/src/common/decorators/validation/is-unique.validator.ts b/src/common/decorators/validation/is-unique.validator.ts index 274a275c..ad00696f 100644 --- a/src/common/decorators/validation/is-unique.validator.ts +++ b/src/common/decorators/validation/is-unique.validator.ts @@ -12,9 +12,9 @@ import { export interface ValidationArguments< Constraints extends unknown[] = [], -Object_ extends object = object, +CustomObject extends object = object, > extends BaseValidationArguments { - object: Object_; + object: CustomObject; constraints: Constraints; } diff --git a/src/common/decorators/validation/transform.decorator.ts b/src/common/decorators/validation/transform.decorator.ts index db9d2a31..1af88ae2 100644 --- a/src/common/decorators/validation/transform.decorator.ts +++ b/src/common/decorators/validation/transform.decorator.ts @@ -1,16 +1,16 @@ import { Transform } from 'class-transformer'; import DOMPurify from 'isomorphic-dompurify'; -import { HelperService } from '@common/helpers'; +import { isArray } from 'helper-fns'; /** -* It trims the value of a property and replaces multiple spaces with a single space -* @returns A function that takes a parameter and returns a value. -*/ + * It trims the value of a property and replaces multiple spaces with a single space + * @returns A function that takes a parameter and returns a value. + */ export const Trim = () => { return Transform((parameters) => { const value = parameters.value as string[] | string; - if (HelperService.isArray(value)) + if (isArray(value)) return value.map((v: string) => v.trim().replaceAll(/\s\s+/g, ' ')); return value.trim().replaceAll(/\s\s+/g, ' '); @@ -18,9 +18,9 @@ export const Trim = () => { }; /** -* It converts a string to a boolean -* @returns A function that returns a PropertyDecorator -*/ + * It converts a string to a boolean + * @returns A function that returns a PropertyDecorator + */ export const ToBoolean = () => { return Transform( @@ -33,7 +33,7 @@ export const ToBoolean = () => { return false; } default: { - return parameters.value; + return parameters.value as boolean; } } }, @@ -42,23 +42,24 @@ export const ToBoolean = () => { }; /** -* It takes a string, sanitizes it, and returns the sanitized string -* @returns A decorator function that will be applied to the class. -*/ + * It takes a string, sanitizes it, and returns the sanitized string + * @returns A decorator function that will be applied to the class. + */ export const Sanitize = (): PropertyDecorator => { return Transform( ({ value }) => { if (Array.isArray(value)) { return value.map((v) => { - if (typeof v === 'string') - return DOMPurify.sanitize(v); + if (typeof v === 'string') return DOMPurify.sanitize(v); return v; - }); + }) as string[]; } - return DOMPurify.sanitize(value); + if (typeof value === 'string') return DOMPurify.sanitize(value); + + return value as string; }, { toClassOnly: true }, ); diff --git a/src/common/guards/jwt.guard.ts b/src/common/guards/jwt.guard.ts index 2372fea6..3c9cfae9 100644 --- a/src/common/guards/jwt.guard.ts +++ b/src/common/guards/jwt.guard.ts @@ -25,7 +25,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') { return super.canActivate(context); } - handleRequest(error: any, user: any, info: any) { + handleRequest(error: any, user: User, info: any) { if (error || info || !user) { if (info instanceof TokenExpiredError) { throw new ForbiddenException( diff --git a/src/common/guards/throttle.guard.ts b/src/common/guards/throttle.guard.ts index 44f0d966..8aa83a0a 100644 --- a/src/common/guards/throttle.guard.ts +++ b/src/common/guards/throttle.guard.ts @@ -1,12 +1,13 @@ import { Injectable } from '@nestjs/common'; import { ThrottlerGuard } from '@nestjs/throttler'; +import type { Request } from 'express'; import { THROTTLE_LIMIT_RESPONSE } from '@common/constant'; @Injectable() export class CustomThrottlerGuard extends ThrottlerGuard { protected errorMessage = THROTTLE_LIMIT_RESPONSE; - protected getTracker(request: Record): string { + protected getTracker(request: Request): string { return request.ips.length > 0 ? request.ips[0] : request.ip; // individualize IP extraction to meet your own needs } } diff --git a/src/common/guards/ws.guard.ts b/src/common/guards/ws.guard.ts index c3262a85..40190a75 100644 --- a/src/common/guards/ws.guard.ts +++ b/src/common/guards/ws.guard.ts @@ -17,7 +17,7 @@ private readonly userRepository: BaseRepository, async canActivate(context: ExecutionContext) { const request = context.switchToWs().getClient().handshake; - const token = request.headers.authorization; + const token: string = request.headers.authorization; const payload: JwtPayload = await this.jwtService.verify(token); const user = await this.userRepository.findOne({ id: payload.sub }); diff --git a/src/common/interceptors/app-exit.interceptor.ts b/src/common/interceptors/app-exit.interceptor.ts index b9e662f9..189ee08f 100644 --- a/src/common/interceptors/app-exit.interceptor.ts +++ b/src/common/interceptors/app-exit.interceptor.ts @@ -11,7 +11,7 @@ export class ExitInterceptor implements NestInterceptor { catchError((error: Error) => { return throwError(() => error); }), - map(data => data), + map((data: unknown) => data), ); } } diff --git a/src/common/interceptors/logger.interceptor.ts b/src/common/interceptors/logger.interceptor.ts index d448c8bd..390c131d 100644 --- a/src/common/interceptors/logger.interceptor.ts +++ b/src/common/interceptors/logger.interceptor.ts @@ -38,7 +38,7 @@ export class LoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, call$: CallHandler): Observable { const request: Request = context.switchToHttp().getRequest(); const { method, url, body, headers } = request; - const context_ = `${this.userPrefix}${this.ctxPrefix} - ${method} - ${url}`; + const logContext = `${this.userPrefix}${this.ctxPrefix} - ${method} - ${url}`; const message = `Request - ${method} - ${url}`; this.logger.log( @@ -48,7 +48,7 @@ export class LoggingInterceptor implements NestInterceptor { body, headers, }, - context_, + logContext, ); return call$.handle().pipe( @@ -73,7 +73,7 @@ export class LoggingInterceptor implements NestInterceptor { const response: Response = context.switchToHttp().getResponse(); const { method, url } = request; const { statusCode } = response; - const context_ = `${this.userPrefix}${this.ctxPrefix} - ${statusCode} - ${method} - ${url}`; + const logContext = `${this.userPrefix}${this.ctxPrefix} - ${statusCode} - ${method} - ${url}`; const message = `Response - ${statusCode} - ${method} - ${url}`; this.logger.log( @@ -81,7 +81,7 @@ export class LoggingInterceptor implements NestInterceptor { message, body, }, - context_, + logContext, ); } @@ -96,7 +96,7 @@ export class LoggingInterceptor implements NestInterceptor { if (error instanceof HttpException) { const statusCode: number = error.getStatus(); - const context_ = `${this.userPrefix}${this.ctxPrefix} - ${statusCode} - ${method} - ${url}`; + const logContext = `${this.userPrefix}${this.ctxPrefix} - ${statusCode} - ${method} - ${url}`; const message = `Response - ${statusCode} - ${method} - ${url}`; if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) { @@ -109,7 +109,7 @@ export class LoggingInterceptor implements NestInterceptor { error, }, error.stack, - context_, + logContext, ); } else { @@ -121,7 +121,7 @@ export class LoggingInterceptor implements NestInterceptor { body, message, }, - context_, + logContext, ); } } diff --git a/src/lib/casl/policies.guard.ts b/src/lib/casl/policies.guard.ts index 1d4f3360..32cc3501 100644 --- a/src/lib/casl/policies.guard.ts +++ b/src/lib/casl/policies.guard.ts @@ -26,14 +26,14 @@ export class PoliciesGuard implements CanActivate { = this.reflector.get(CHECK_POLICIES_KEY_META, context.getHandler()) || []; - const request = context.switchToHttp().getRequest(); + const request: Request = context.switchToHttp().getRequest(); const { user } = request; const ability = this.caslAbilityFactory.createForUser(user); return policyHandlers.every(handler => - this.execPolicyHandler(handler, request as Request, ability), + this.execPolicyHandler(handler, request, ability), ); } diff --git a/src/lib/pino/pino.module.ts b/src/lib/pino/pino.module.ts index 02ce3c2b..e00d7247 100644 --- a/src/lib/pino/pino.module.ts +++ b/src/lib/pino/pino.module.ts @@ -22,7 +22,7 @@ const basePinoOptions = { context: 'HTTP', }), serializers: { - req(request) { + req(request: Record) { request.body = request.raw.body; return request; diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 475f5684..4b771564 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -153,7 +153,7 @@ private readonly em: EntityManager, * @param {string} refreshToken - The refresh token that was sent to the client. * @returns Observable */ - logout(user: User, refreshToken: string): Observable { + logout(user: User, refreshToken: string): Observable { return from(this.tokenService.decodeRefreshToken(refreshToken)).pipe( switchMap((payload) => { return this.tokenService.deleteRefreshToken(user, payload);