Skip to content

Commit

Permalink
fix: lint
Browse files Browse the repository at this point in the history
  • Loading branch information
rubiin committed Aug 14, 2023
1 parent a6a881a commit 8525d9b
Show file tree
Hide file tree
Showing 15 changed files with 47 additions and 42 deletions.
3 changes: 3 additions & 0 deletions src/common/@types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ namespace Express {
export interface Request {
user?: UserEntity;
realIp: string;
body : Record<string, any>;
ip: string;
ips: string[];
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/common/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
6 changes: 3 additions & 3 deletions src/common/decorators/validation/is-date-format.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
6 changes: 3 additions & 3 deletions src/common/decorators/validation/is-unique.validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('IsUnique', () => {
const mockEm = createMock<EntityManager>();
const username = 'tester';

const arguments_: IsUniqueValidationContext = {
const validatorArguments: IsUniqueValidationContext = {
object: { username },
constraints: [() => User, 'username' as never],
value: username,
Expand All @@ -29,15 +29,15 @@ describe('IsUnique', () => {

it('should pass if there are no duplicates', async () => {
mockEm.count.mockResolvedValue(0);
const result = await isUnique.validate<User, 'username'>(username, arguments_);
const result = await isUnique.validate<User, 'username'>(username, validatorArguments);

expect(result).toBeTruthy();
expect(mockEm.count).toBeCalledWith(User, { username });
});

it('should fail if there are duplicates', async () => {
mockEm.count.mockResolvedValue(1);
const result = await isUnique.validate<User, 'username'>(username, arguments_);
const result = await isUnique.validate<User, 'username'>(username, validatorArguments);

expect(result).toBeFalsy();
expect(mockEm.count).toBeCalledWith(User, { username });
Expand Down
4 changes: 2 additions & 2 deletions src/common/decorators/validation/is-unique.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
33 changes: 17 additions & 16 deletions src/common/decorators/validation/transform.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
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, ' ');
});
};

/**
* 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(
Expand All @@ -33,7 +33,7 @@ export const ToBoolean = () => {
return false;
}
default: {
return parameters.value;
return parameters.value as boolean;
}
}
},
Expand All @@ -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 },
);
Expand Down
2 changes: 1 addition & 1 deletion src/common/guards/jwt.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
return super.canActivate(context);
}

handleRequest(error: any, user: any, info: any) {
handleRequest<User>(error: any, user: User, info: any) {
if (error || info || !user) {
if (info instanceof TokenExpiredError) {
throw new ForbiddenException(
Expand Down
3 changes: 2 additions & 1 deletion src/common/guards/throttle.guard.ts
Original file line number Diff line number Diff line change
@@ -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, any>): string {
protected getTracker(request: Request): string {
return request.ips.length > 0 ? request.ips[0] : request.ip; // individualize IP extraction to meet your own needs
}
}
2 changes: 1 addition & 1 deletion src/common/guards/ws.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ private readonly userRepository: BaseRepository<User>,

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 });
Expand Down
2 changes: 1 addition & 1 deletion src/common/interceptors/app-exit.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class ExitInterceptor implements NestInterceptor {
catchError((error: Error) => {
return throwError(() => error);
}),
map(data => data),
map((data: unknown) => data),
);
}
}
14 changes: 7 additions & 7 deletions src/common/interceptors/logger.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, call$: CallHandler): Observable<unknown> {
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(
Expand All @@ -48,7 +48,7 @@ export class LoggingInterceptor implements NestInterceptor {
body,
headers,
},
context_,
logContext,
);

return call$.handle().pipe(
Expand All @@ -73,15 +73,15 @@ export class LoggingInterceptor implements NestInterceptor {
const response: Response = context.switchToHttp().getResponse<Response>();
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(
{
message,
body,
},
context_,
logContext,
);
}

Expand All @@ -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) {
Expand All @@ -109,7 +109,7 @@ export class LoggingInterceptor implements NestInterceptor {
error,
},
error.stack,
context_,
logContext,
);
}
else {
Expand All @@ -121,7 +121,7 @@ export class LoggingInterceptor implements NestInterceptor {
body,
message,
},
context_,
logContext,
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/casl/policies.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ export class PoliciesGuard implements CanActivate {
= this.reflector.get<PolicyHandler[]>(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),
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib/pino/pino.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const basePinoOptions = {
context: 'HTTP',
}),
serializers: {
req(request) {
req(request: Record<string, any>) {
request.body = request.raw.body;

return request;
Expand Down
2 changes: 1 addition & 1 deletion src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private readonly em: EntityManager,
* @param {string} refreshToken - The refresh token that was sent to the client.
* @returns Observable<any>
*/
logout(user: User, refreshToken: string): Observable<any> {
logout(user: User, refreshToken: string): Observable<User> {
return from(this.tokenService.decodeRefreshToken(refreshToken)).pipe(
switchMap((payload) => {
return this.tokenService.deleteRefreshToken(user, payload);
Expand Down

0 comments on commit 8525d9b

Please sign in to comment.