From 793c4c335084b31101f8bf354404572ef62bd440 Mon Sep 17 00:00:00 2001 From: moesjarraf Date: Wed, 22 Feb 2023 15:54:29 +0100 Subject: [PATCH] style: lint and format project --- README.md | 4 -- src/app/app.controller.ts | 4 +- src/app/app.module.ts | 5 +- src/app/app.providers.ts | 2 +- src/app/classes/main.class.ts | 2 +- src/common.module.ts | 26 +++++++-- src/filters/common-exception.filter.ts | 10 +++- src/filters/exception.module.ts | 7 +-- src/filters/http-exception.filter.ts | 53 +++++++++++-------- src/filters/index-exception.filter.ts | 15 +++++- src/filters/internal-exception.filter.ts | 46 +++++++++------- src/modules/captcha/captcha.guard.ts | 14 +++-- src/modules/captcha/captcha.middleware.ts | 14 ++--- src/modules/captcha/captcha.module.ts | 2 +- src/modules/captcha/captcha.service.spec.ts | 6 --- src/modules/captcha/captcha.service.ts | 6 ++- src/modules/config/config.module.ts | 2 +- src/modules/config/config.service.ts | 30 ++++++----- src/modules/emitter/emitter.module.ts | 12 ++--- src/modules/emitter/emitter.providers.ts | 3 +- src/modules/emitter/emitter.service.ts | 15 +++--- src/modules/http-auth/http-auth.decorator.ts | 8 +-- src/modules/http-auth/http-auth.guard.ts | 7 ++- src/modules/http-auth/http-auth.middleware.ts | 2 +- src/modules/http-auth/http-auth.module.ts | 14 ++--- .../http-auth/http-auth.service.spec.ts | 12 +++-- src/modules/http-auth/http-auth.service.ts | 6 ++- src/modules/logger/logger-builder.service.ts | 47 +++++++++------- src/modules/logger/logger.module.ts | 14 ++--- src/modules/logger/logger.service.spec.ts | 7 +-- src/modules/logger/logger.service.ts | 27 +++++++--- src/modules/logger/utils/colors.utils.ts | 20 +++++-- src/modules/mailer/mailer.module.ts | 12 ++--- src/modules/mailer/mailer.providers.ts | 3 +- src/modules/mailer/mailer.service.ts | 29 +++++----- src/modules/request/request.module.ts | 18 ++----- src/modules/request/request.providers.ts | 3 +- src/modules/request/request.service.spec.ts | 42 ++++++++++----- src/modules/request/request.service.ts | 37 ++++++++++--- src/modules/ssl/ssl.middleware.spec.ts | 3 -- src/modules/ssl/ssl.middleware.ts | 3 +- src/modules/ssl/ssl.module.ts | 17 ++---- src/modules/ssl/ssl.service.spec.ts | 23 ++++---- src/modules/ssl/ssl.service.ts | 11 ++-- src/utils/file-exists.util.ts | 5 +- test/app.e2e-spec.ts | 19 +++++-- 46 files changed, 382 insertions(+), 285 deletions(-) diff --git a/README.md b/README.md index c905169..a5c4c80 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,6 @@ $ npm install @moesjarraf/nestjs-common See [this](https://github.com/moesjarraf/nestjs-example) repository for an example. -## Documentation - -todo - ## Development Commit messages should be formatted according to semantic-release standards, see [this](https://github.com/semantic-release/semantic-release#commit-message-format) link for more information. A tool has been added to the project to make adhering to the standards easier. diff --git a/src/app/app.controller.ts b/src/app/app.controller.ts index a105a96..03e377c 100644 --- a/src/app/app.controller.ts +++ b/src/app/app.controller.ts @@ -6,9 +6,7 @@ import { fileExists } from '../utils/file-exists.util'; @Controller() export class AppController { - constructor( - protected readonly config: ConfigService, - ) { } + constructor(protected readonly config: ConfigService) {} @Get() @ApiExcludeEndpoint() diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 2a85fa7..7c05f02 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -15,9 +15,6 @@ export const AppModuleConfig = { @Module(AppModuleConfig) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { - consumer.apply( - SSLMiddleware, - HttpAuthMiddleware, - ).forRoutes('*'); + consumer.apply(SSLMiddleware, HttpAuthMiddleware).forRoutes('*'); } } diff --git a/src/app/app.providers.ts b/src/app/app.providers.ts index 25f8893..993e3eb 100644 --- a/src/app/app.providers.ts +++ b/src/app/app.providers.ts @@ -5,5 +5,5 @@ export const commonAppProviders = [ { provide: APP_FILTER, useClass: IndexExceptionFilter, - } + }, ]; diff --git a/src/app/classes/main.class.ts b/src/app/classes/main.class.ts index 4bd4884..63e4e00 100644 --- a/src/app/classes/main.class.ts +++ b/src/app/classes/main.class.ts @@ -1,4 +1,4 @@ -import { INestApplication, NestModule } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; diff --git a/src/common.module.ts b/src/common.module.ts index e7de735..a333259 100644 --- a/src/common.module.ts +++ b/src/common.module.ts @@ -12,17 +12,33 @@ import { SSLModule } from './modules/ssl/ssl.module'; export const CommonModuleConfig = { imports: [ - ConfigModule, LoggerModule, RequestModule, EmitterModule, DatabaseModule, - SSLModule, MailerModule, HttpAuthModule, ExceptionModule, CaptchaModule, + ConfigModule, + LoggerModule, + RequestModule, + EmitterModule, + DatabaseModule, + SSLModule, + MailerModule, + HttpAuthModule, + ExceptionModule, + CaptchaModule, ], controllers: [], providers: [], exports: [ - ConfigModule, LoggerModule, RequestModule, EmitterModule, DatabaseModule, - SSLModule, MailerModule, HttpAuthModule, ExceptionModule, CaptchaModule, + ConfigModule, + LoggerModule, + RequestModule, + EmitterModule, + DatabaseModule, + SSLModule, + MailerModule, + HttpAuthModule, + ExceptionModule, + CaptchaModule, ], }; @Global() @Module(CommonModuleConfig) -export class CommonModule { } +export class CommonModule {} diff --git a/src/filters/common-exception.filter.ts b/src/filters/common-exception.filter.ts index 18c1c3a..f07d7ae 100644 --- a/src/filters/common-exception.filter.ts +++ b/src/filters/common-exception.filter.ts @@ -1,6 +1,12 @@ import { ConfigService } from '../modules/config/config.service'; import { LoggerService } from '../modules/logger/logger.service'; -import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Injectable } from '@nestjs/common'; +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + Injectable, +} from '@nestjs/common'; import { HttpExceptionFilter } from './http-exception.filter'; import { InternalExceptionFilter } from './internal-exception.filter'; @@ -13,7 +19,7 @@ export class CommonExceptionFilter implements ExceptionFilter { public readonly httpException: HttpExceptionFilter, public readonly internalException: InternalExceptionFilter, ) { - this.logger = this.logger.build(CommonExceptionFilter.name) + this.logger = this.logger.build(CommonExceptionFilter.name); } async catch(exception: Error, host: ArgumentsHost) { diff --git a/src/filters/exception.module.ts b/src/filters/exception.module.ts index 6b3d1d6..07e708b 100644 --- a/src/filters/exception.module.ts +++ b/src/filters/exception.module.ts @@ -7,10 +7,7 @@ import { ConfigModule } from '../modules/config/config.module'; import { LoggerModule } from '../modules/logger/logger.module'; export const ExceptionModuleConfig = { - imports: [ - ConfigModule, - LoggerModule, - ], + imports: [ConfigModule, LoggerModule], controllers: [], providers: [ HttpExceptionFilter, @@ -27,4 +24,4 @@ export const ExceptionModuleConfig = { }; @Module(ExceptionModuleConfig) -export class ExceptionModule { } +export class ExceptionModule {} diff --git a/src/filters/http-exception.filter.ts b/src/filters/http-exception.filter.ts index cd2156a..b48c2e4 100644 --- a/src/filters/http-exception.filter.ts +++ b/src/filters/http-exception.filter.ts @@ -1,7 +1,14 @@ import { snakeCase } from 'snake-case'; import { ExceptionCodeI18n } from './../modules/exception/i18n/code.i18n'; import { LoggerService } from './../modules/logger/logger.service'; -import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Injectable } from '@nestjs/common'; +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + HttpStatus, + Injectable, +} from '@nestjs/common'; import { InternalExceptionFilter } from './internal-exception.filter'; @Injectable() @@ -11,7 +18,7 @@ export class HttpExceptionFilter implements ExceptionFilter { private readonly logger: LoggerService, private readonly internalException: InternalExceptionFilter, ) { - this.logger = this.logger.build(HttpExceptionFilter.name) + this.logger = this.logger.build(HttpExceptionFilter.name); } async catch(exception: HttpException, host: ArgumentsHost) { @@ -27,28 +34,32 @@ export class HttpExceptionFilter implements ExceptionFilter { const path = request.path; const method = request.method; const exResponse = exception.getResponse() as any; - const message = typeof exResponse === 'string' || Array.isArray(exResponse) ? - exResponse : (exResponse.message || exResponse.error); + const message = + typeof exResponse === 'string' || Array.isArray(exResponse) + ? exResponse + : exResponse.message || exResponse.error; const stack = exception.stack; const locale = request.locale; const type = typeof message === 'string' ? snakeCase(message) : undefined; - const translation = ExceptionCodeI18n[type]?.[locale] || - ExceptionCodeI18n[HttpStatus[type?.toUpperCase?.()]]?.[locale]; - - this.logger.debug(`'[${method}] ${path} (${status})' failed with ${message}`, { - stack: stack || null + const translation = + ExceptionCodeI18n[type]?.[locale] || + ExceptionCodeI18n[HttpStatus[type?.toUpperCase?.()]]?.[locale]; + + this.logger.debug( + `'[${method}] ${path} (${status})' failed with ${message}`, + { + stack: stack || null, + }, + ); + + response.status(status).json({ + path, + method, + code: status, + message: typeof message !== 'string' ? undefined : translation || message, + error: typeof message !== 'string' ? message : undefined, + type: translation ? type : undefined, + time, }); - - response - .status(status) - .json({ - path, - method, - code: status, - message: typeof message !== 'string' ? undefined : translation || message, - error: typeof message !== 'string' ? message : undefined, - type: translation ? type : undefined, - time, - }); } } diff --git a/src/filters/index-exception.filter.ts b/src/filters/index-exception.filter.ts index 41eeb63..945128e 100644 --- a/src/filters/index-exception.filter.ts +++ b/src/filters/index-exception.filter.ts @@ -1,5 +1,11 @@ import { ConfigService } from './../modules/config/config.service'; -import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Injectable } from '@nestjs/common'; +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + Injectable, +} from '@nestjs/common'; import { HttpExceptionFilter } from './http-exception.filter'; import { LoggerService } from '../modules/logger/logger.service'; import { fileExists } from '../utils/file-exists.util'; @@ -23,7 +29,12 @@ export class IndexExceptionFilter implements ExceptionFilter { const path = request.path; const index = this.config.frontend.index; - if (status === 404 && index && !path.startsWith('/api') && await fileExists(index)) { + if ( + status === 404 && + index && + !path.startsWith('/api') && + (await fileExists(index)) + ) { return response.sendFile(index); } diff --git a/src/filters/internal-exception.filter.ts b/src/filters/internal-exception.filter.ts index 3b416b8..8aa02f0 100644 --- a/src/filters/internal-exception.filter.ts +++ b/src/filters/internal-exception.filter.ts @@ -2,7 +2,13 @@ import { ExceptionCodeI18n } from './../modules/exception/i18n/code.i18n'; import { snakeCase } from 'snake-case'; import { ConfigService } from './../modules/config/config.service'; import { LoggerService } from './../modules/logger/logger.service'; -import { ExceptionFilter, Catch, ArgumentsHost, Injectable, HttpStatus } from '@nestjs/common'; +import { + ExceptionFilter, + Catch, + ArgumentsHost, + Injectable, + HttpStatus, +} from '@nestjs/common'; @Injectable() @Catch() @@ -11,7 +17,7 @@ export class InternalExceptionFilter implements ExceptionFilter { private readonly logger: LoggerService, private readonly config: ConfigService, ) { - this.logger = this.logger.build(InternalExceptionFilter.name) + this.logger = this.logger.build(InternalExceptionFilter.name); } async catch(exception: Error, host: ArgumentsHost) { @@ -22,27 +28,31 @@ export class InternalExceptionFilter implements ExceptionFilter { const status = 500; const path = request.path; const method = request.method; - const message = this.config.debug ? exception.message : 'internal server error'; + const message = this.config.debug + ? exception.message + : 'internal server error'; const stack = exception.stack; const locale = request.locale; const type = typeof message === 'string' ? snakeCase(message) : undefined; - const translation = ExceptionCodeI18n[type]?.[locale] || + const translation = + ExceptionCodeI18n[type]?.[locale] || ExceptionCodeI18n[HttpStatus[type?.toUpperCase?.()]]?.[locale]; - this.logger.error(`'[${method}] ${path} (${status})' failed with ${message}`, { - stack: stack || null - }); + this.logger.error( + `'[${method}] ${path} (${status})' failed with ${message}`, + { + stack: stack || null, + }, + ); - response - .status(status) - .json({ - path, - method, - code: status, - message: typeof message !== 'string' ? undefined : translation || message, - error: typeof message !== 'string' ? message : undefined, - type: translation ? type : undefined, - time, - }); + response.status(status).json({ + path, + method, + code: status, + message: typeof message !== 'string' ? undefined : translation || message, + error: typeof message !== 'string' ? message : undefined, + type: translation ? type : undefined, + time, + }); } } diff --git a/src/modules/captcha/captcha.guard.ts b/src/modules/captcha/captcha.guard.ts index 3c98313..b84422b 100644 --- a/src/modules/captcha/captcha.guard.ts +++ b/src/modules/captcha/captcha.guard.ts @@ -1,11 +1,14 @@ -import { BadRequestException, CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import { + BadRequestException, + CanActivate, + ExecutionContext, + Injectable, +} from '@nestjs/common'; import { Request } from 'express'; import { ExceptionCodeEnum } from '../exception/enums/code.enum'; - @Injectable() export class CaptchaGuard implements CanActivate { - async canActivate(context: ExecutionContext) { const request = context.switchToHttp().getRequest() as Request; @@ -14,10 +17,11 @@ export class CaptchaGuard implements CanActivate { } if (!(request as any).captchaValid) { - throw new BadRequestException(ExceptionCodeEnum.InvalidCaptchaResponseGiven); + throw new BadRequestException( + ExceptionCodeEnum.InvalidCaptchaResponseGiven, + ); } return true; } - } diff --git a/src/modules/captcha/captcha.middleware.ts b/src/modules/captcha/captcha.middleware.ts index 2d96187..93268d2 100644 --- a/src/modules/captcha/captcha.middleware.ts +++ b/src/modules/captcha/captcha.middleware.ts @@ -4,13 +4,15 @@ import { CaptchaService } from './captcha.service'; @Injectable() export class CaptchaMiddleware implements NestMiddleware { - constructor(private readonly captcha: CaptchaService) { - } + constructor(private readonly captcha: CaptchaService) {} use(req: Request, res: Response, next: () => void): any { - this.captcha.validate(req.body.captcha_response).then(({ success }) => { - (req as any).captchaValid = success; - next(); - }).catch(next); + this.captcha + .validate(req.body.captcha_response) + .then(({ success }) => { + (req as any).captchaValid = success; + next(); + }) + .catch(next); } } diff --git a/src/modules/captcha/captcha.module.ts b/src/modules/captcha/captcha.module.ts index 276c58d..4cedbaa 100644 --- a/src/modules/captcha/captcha.module.ts +++ b/src/modules/captcha/captcha.module.ts @@ -24,4 +24,4 @@ export const CaptchaModuleConfig = { }; @Module(CaptchaModuleConfig) -export class CaptchaModule { } +export class CaptchaModule {} diff --git a/src/modules/captcha/captcha.service.spec.ts b/src/modules/captcha/captcha.service.spec.ts index a4bc005..002a159 100644 --- a/src/modules/captcha/captcha.service.spec.ts +++ b/src/modules/captcha/captcha.service.spec.ts @@ -6,13 +6,8 @@ import { RECAPTCHA } from '../../constants'; describe('CaptchaService', () => { let module: TestingModule; let captchaService: CaptchaService; - let spies: ReturnType; let providers: ReturnType; - function spy() { - return {}; - } - function provide() { const captchaInstance = jest.fn(); const recaptcha = jest.fn(() => captchaInstance); @@ -30,7 +25,6 @@ describe('CaptchaService', () => { await module.init(); captchaService = module.get(CaptchaService); - spies = spy(); }); afterEach(async () => { diff --git a/src/modules/captcha/captcha.service.ts b/src/modules/captcha/captcha.service.ts index 7c57ece..1928328 100644 --- a/src/modules/captcha/captcha.service.ts +++ b/src/modules/captcha/captcha.service.ts @@ -11,7 +11,7 @@ export class CaptchaService { private readonly logger: LoggerService, @Inject(RECAPTCHA) private readonly recaptcha: typeof recaptcha2, ) { - this.logger = this.logger.build(CaptchaService.name) + this.logger = this.logger.build(CaptchaService.name); } isEnabled(): boolean { @@ -32,7 +32,9 @@ export class CaptchaService { }); } - async validate(response: string): Promise<{ success: boolean, errors: string[] }> { + async validate( + response: string, + ): Promise<{ success: boolean; errors: string[] }> { const result = { success: true, errors: [] }; if (!this.isEnabled()) { diff --git a/src/modules/config/config.module.ts b/src/modules/config/config.module.ts index 7ad65c0..e518dbb 100644 --- a/src/modules/config/config.module.ts +++ b/src/modules/config/config.module.ts @@ -21,4 +21,4 @@ import { ConfigModule as NestConfigModule } from '@nestjs/config'; providers: [ConfigService], exports: [ConfigService], }) -export class ConfigModule { } +export class ConfigModule {} diff --git a/src/modules/config/config.service.ts b/src/modules/config/config.service.ts index 2489178..be00fae 100644 --- a/src/modules/config/config.service.ts +++ b/src/modules/config/config.service.ts @@ -18,9 +18,8 @@ export class ConfigService extends NestConfigService { return { env: nodeEnv, - isEnv: (env: string | string[]) => typeof env === 'string' ? - env === nodeEnv : - env.includes(nodeEnv), + isEnv: (env: string | string[]) => + typeof env === 'string' ? env === nodeEnv : env.includes(nodeEnv), }; } @@ -39,16 +38,17 @@ export class ConfigService extends NestConfigService { return { index: indexFullPath, dist: indexFullPath ? dirname(indexFullPath) : undefined, - } + }; } get cors() { const origin = (this.get('CORS_ORIGIN') || '*') .split(',') - .map((string) => string !== '*' ? new RegExp(string) : string); + .map((string) => (string !== '*' ? new RegExp(string) : string)); const credentials = boolean(this.get('CORS_CREDENTIALS')) || false; - const exposedHeaders = this.get('CORS_EXPOSED_HEADERS') || undefined; + const exposedHeaders = + this.get('CORS_EXPOSED_HEADERS') || undefined; return { origin, @@ -58,13 +58,15 @@ export class ConfigService extends NestConfigService { } get body_parser() { - const paths = (this.get('BODY_PARSER_RAW_PATHS') || ''); + const paths = this.get('BODY_PARSER_RAW_PATHS') || ''; return { - isRawPath: (path) => paths.split(',') - .map((item) => path.match(item)) - .filter((item) => Boolean(item)), - } + isRawPath: (path) => + paths + .split(',') + .map((item) => path.match(item)) + .filter((item) => Boolean(item)), + }; } get captcha() { @@ -77,7 +79,9 @@ export class ConfigService extends NestConfigService { get mongo() { return { - default_url: this.get('MONGO_DEFAULT_URL') || 'mongodb://0.0.0.0:27017/nestjs', + default_url: + this.get('MONGO_DEFAULT_URL') || + 'mongodb://0.0.0.0:27017/nestjs', }; } @@ -112,7 +116,7 @@ export class ConfigService extends NestConfigService { user: this.get('MAILER_USER'), pass: this.get('MAILER_PASS'), }, - } + }; } get ssl() { diff --git a/src/modules/emitter/emitter.module.ts b/src/modules/emitter/emitter.module.ts index fa236e2..ef8c504 100644 --- a/src/modules/emitter/emitter.module.ts +++ b/src/modules/emitter/emitter.module.ts @@ -7,15 +7,9 @@ import { ConfigModule } from '../config/config.module'; export const EmitterModuleConfig = { imports: [LoggerModule, ConfigModule], controllers: [], - providers: [ - ...emitterProviders, - EmitterService, - ], - exports: [ - ...emitterProviders, - EmitterService, - ], + providers: [...emitterProviders, EmitterService], + exports: [...emitterProviders, EmitterService], }; @Module(EmitterModuleConfig) -export class EmitterModule { } +export class EmitterModule {} diff --git a/src/modules/emitter/emitter.providers.ts b/src/modules/emitter/emitter.providers.ts index a47884a..2f102bb 100644 --- a/src/modules/emitter/emitter.providers.ts +++ b/src/modules/emitter/emitter.providers.ts @@ -1,2 +1 @@ -export const emitterProviders = [ -]; +export const emitterProviders = []; diff --git a/src/modules/emitter/emitter.service.ts b/src/modules/emitter/emitter.service.ts index c5d4cdf..57716e7 100644 --- a/src/modules/emitter/emitter.service.ts +++ b/src/modules/emitter/emitter.service.ts @@ -5,8 +5,6 @@ import { Subject } from 'rxjs'; export class EmitterService implements OnModuleDestroy { private subjects = new Map>(); - constructor() { } - emit(event: keyof T, data: T[keyof T]) { // @todo: make it possible to await the emit so you can be notified if the listeners are all done const key = event as string; @@ -34,7 +32,7 @@ export class EmitterService implements OnModuleDestroy { const cb = (val: T[keyof T]) => { this.off(event, cb); return callback(val); - } + }; this.on(event, cb); } @@ -42,18 +40,21 @@ export class EmitterService implements OnModuleDestroy { if (!this.subjects.has(event as string)) return; const { observers } = this.subjects.get(event as string); - const index = observers - .findIndex((ob: any) => ob._subscriptions.some(any => any.subscriber.destination._next === callback)) + const index = observers.findIndex((ob: any) => + ob._subscriptions.some( + (any) => any.subscriber.destination._next === callback, + ), + ); if (index > -1) observers.splice(index, 1); } waitFor(event: keyof T) { - return new Promise(resolve => this.once(event, resolve)) + return new Promise((resolve) => this.once(event, resolve)); } onModuleDestroy() { - for (const [key, subject] of this.subjects) { + for (const [, subject] of this.subjects) { subject.unsubscribe(); } diff --git a/src/modules/http-auth/http-auth.decorator.ts b/src/modules/http-auth/http-auth.decorator.ts index bbd2b23..24e3207 100644 --- a/src/modules/http-auth/http-auth.decorator.ts +++ b/src/modules/http-auth/http-auth.decorator.ts @@ -1,6 +1,8 @@ import { createParamDecorator } from '@nestjs/common'; import { Request } from 'express'; -export const HttpAuthDecorator = createParamDecorator((data: any, req: Request) => { - return (req as any).authorization; -}); +export const HttpAuthDecorator = createParamDecorator( + (data: any, req: Request) => { + return (req as any).authorization; + }, +); diff --git a/src/modules/http-auth/http-auth.guard.ts b/src/modules/http-auth/http-auth.guard.ts index 77b3f90..0e287be 100644 --- a/src/modules/http-auth/http-auth.guard.ts +++ b/src/modules/http-auth/http-auth.guard.ts @@ -1,5 +1,10 @@ import { HttpAuthResultInterface } from './interfaces/auth-result.interface'; -import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common'; +import { + Injectable, + CanActivate, + ExecutionContext, + UnauthorizedException, +} from '@nestjs/common'; import { Request } from 'express'; @Injectable() diff --git a/src/modules/http-auth/http-auth.middleware.ts b/src/modules/http-auth/http-auth.middleware.ts index 01e449a..89c1db7 100644 --- a/src/modules/http-auth/http-auth.middleware.ts +++ b/src/modules/http-auth/http-auth.middleware.ts @@ -4,7 +4,7 @@ import { HttpAuthService } from './http-auth.service'; @Injectable() export class HttpAuthMiddleware implements NestMiddleware { - constructor(private readonly httpAuth: HttpAuthService) { } + constructor(private readonly httpAuth: HttpAuthService) {} async use(req: Request, res: Response, next: NextFunction) { const token = req.header('authorization'); diff --git a/src/modules/http-auth/http-auth.module.ts b/src/modules/http-auth/http-auth.module.ts index 4ba28e0..69c9170 100644 --- a/src/modules/http-auth/http-auth.module.ts +++ b/src/modules/http-auth/http-auth.module.ts @@ -6,17 +6,9 @@ import { HttpAuthService } from './http-auth.service'; export const HttpAuthModuleConfig = { imports: [ConfigModule], - providers: [ - HttpAuthService, - HttpAuthMiddleware, - HttpAuthGuard, - ], - exports: [ - HttpAuthService, - HttpAuthMiddleware, - HttpAuthGuard, - ], + providers: [HttpAuthService, HttpAuthMiddleware, HttpAuthGuard], + exports: [HttpAuthService, HttpAuthMiddleware, HttpAuthGuard], }; @Module(HttpAuthModuleConfig) -export class HttpAuthModule { } +export class HttpAuthModule {} diff --git a/src/modules/http-auth/http-auth.service.spec.ts b/src/modules/http-auth/http-auth.service.spec.ts index e689e0f..fc45611 100644 --- a/src/modules/http-auth/http-auth.service.spec.ts +++ b/src/modules/http-auth/http-auth.service.spec.ts @@ -16,16 +16,20 @@ describe('HttpAuthService', () => { describe('validateBearer()', () => { test('should return true if a token is correct', () => { - const token = 'A0qA!YGeE!F2uNsbMl$BVw52StGgDNHv@K6j6i3iilr1qWvB*P4nm2KkjbvVu55U'; - jest.spyOn(ConfigService.prototype, 'http_auth', 'get').mockImplementation(() => ({ bearer_token: token })); - + const token = + 'A0qA!YGeE!F2uNsbMl$BVw52StGgDNHv@K6j6i3iilr1qWvB*P4nm2KkjbvVu55U'; + jest + .spyOn(ConfigService.prototype, 'http_auth', 'get') + .mockImplementation(() => ({ bearer_token: token })); expect(authService.validateBearer(token)).toEqual({ authorized: true }); }); test('should return false if a token is incorrect', () => { const token = 'test'; - jest.spyOn(ConfigService.prototype, 'http_auth', 'get').mockImplementation(() => ({ bearer_token: 'test1234' })); + jest + .spyOn(ConfigService.prototype, 'http_auth', 'get') + .mockImplementation(() => ({ bearer_token: 'test1234' })); expect(authService.validateBearer(token)).toEqual({ authorized: false }); }); diff --git a/src/modules/http-auth/http-auth.service.ts b/src/modules/http-auth/http-auth.service.ts index fed2549..9170974 100644 --- a/src/modules/http-auth/http-auth.service.ts +++ b/src/modules/http-auth/http-auth.service.ts @@ -4,9 +4,11 @@ import { ConfigService } from '../config/config.service'; @Injectable() export class HttpAuthService { - constructor(private readonly config: ConfigService) { } + constructor(private readonly config: ConfigService) {} - validate(token: string): ReturnType { + validate( + token: string, + ): ReturnType { if (token.match('bearer')) { return this.validateBearer(token); } diff --git a/src/modules/logger/logger-builder.service.ts b/src/modules/logger/logger-builder.service.ts index 3b4b4c1..8be705b 100644 --- a/src/modules/logger/logger-builder.service.ts +++ b/src/modules/logger/logger-builder.service.ts @@ -28,7 +28,9 @@ export class LoggerBuilderService { createLogger(): winston.Logger { const formats = [ - this._winston.format.label({ label: pascalCase(this.config.app.short_name) }), + this._winston.format.label({ + label: pascalCase(this.config.app.short_name), + }), this._winston.format.timestamp({ format: 'DD/MM/YY hh:mm:ss' }), this._winston.format.printf((info) => { const msg = [ @@ -36,17 +38,24 @@ export class LoggerBuilderService { LoggerColorUtils.clc.cyanBright(`[${info.label}] `), `<${info.timestamp}>\t`, `${info.level}\t`, - info.context ? LoggerColorUtils.clc.yellow(`[${info.context}] `) : '', + info.context + ? LoggerColorUtils.clc.yellow(`[${info.context}] `) + : '', `${info.message}`, - ].join('') + ].join(''), ]; for (const key in info) { - if (['timestamp', 'message', 'level', 'label', 'context'].indexOf(key) > -1) { + if ( + ['timestamp', 'message', 'level', 'label', 'context'].indexOf(key) > + -1 + ) { continue; } - const value = util.isString(info[key]) ? info[key] : Flatted.stringify(info[key], null, 2); + const value = util.isString(info[key]) + ? info[key] + : Flatted.stringify(info[key], null, 2); msg.push(`\n${key}:\n${value}\n`); } @@ -58,7 +67,7 @@ export class LoggerBuilderService { new this._winston.transports.Console({ level: this.config.logger.level, format: this._winston.format.combine( - this._winston.format(info => { + this._winston.format((info) => { info.level = `<${info.level}>`; return info; })(), @@ -66,22 +75,24 @@ export class LoggerBuilderService { ...formats, ), handleExceptions: true, - }) + }), ]; const rollbar = this.config.rollbar; if (rollbar.access_token) { - transports.push(new RollbarTransport({ - rollbarConfig: { - accessToken: rollbar.access_token, - environment: rollbar.environment || this.config.node.env, - reportLevel: rollbar.level || 'warn', - captureUncaught: true, - captureUnhandledRejections: true, - uncaughtErrorLevel: 'critical', - }, - level: rollbar.level || 'warn', - })); + transports.push( + new RollbarTransport({ + rollbarConfig: { + accessToken: rollbar.access_token, + environment: rollbar.environment || this.config.node.env, + reportLevel: rollbar.level || 'warn', + captureUncaught: true, + captureUnhandledRejections: true, + uncaughtErrorLevel: 'critical', + }, + level: rollbar.level || 'warn', + }), + ); } return this._winston.createLogger({ diff --git a/src/modules/logger/logger.module.ts b/src/modules/logger/logger.module.ts index 0bd93a8..7d127d8 100644 --- a/src/modules/logger/logger.module.ts +++ b/src/modules/logger/logger.module.ts @@ -7,17 +7,9 @@ import { ConfigModule } from '../config/config.module'; export const LoggerModuleConfig = { imports: [ConfigModule], controllers: [], - providers: [ - ...loggerProviders, - LoggerBuilderService, - LoggerService, - ], - exports: [ - ...loggerProviders, - LoggerBuilderService, - LoggerService, - ], + providers: [...loggerProviders, LoggerBuilderService, LoggerService], + exports: [...loggerProviders, LoggerBuilderService, LoggerService], }; @Module(LoggerModuleConfig) -export class LoggerModule { } +export class LoggerModule {} diff --git a/src/modules/logger/logger.service.spec.ts b/src/modules/logger/logger.service.spec.ts index 61ff17b..20029d2 100644 --- a/src/modules/logger/logger.service.spec.ts +++ b/src/modules/logger/logger.service.spec.ts @@ -15,8 +15,7 @@ describe('LoggerService', () => { } beforeEach(async () => { - module = await Test.createTestingModule(LoggerModuleConfig) - .compile(); + module = await Test.createTestingModule(LoggerModuleConfig).compile(); await module.init(); loggerService = module.get(LoggerService); @@ -26,10 +25,6 @@ describe('LoggerService', () => { await module.close(); }); - describe('log()', () => { - test.skip('should log with given level', async () => { }); - }); - describe('info()', () => { test('should log with info level', async () => { const spies = spy(); diff --git a/src/modules/logger/logger.service.ts b/src/modules/logger/logger.service.ts index 72b9ef0..2696683 100644 --- a/src/modules/logger/logger.service.ts +++ b/src/modules/logger/logger.service.ts @@ -9,7 +9,7 @@ export class LoggerService { constructor( private readonly loggerBuilder: LoggerBuilderService, @Optional() private readonly context?: string, - ) { } + ) {} build(context?: string | object) { if (typeof context === 'object' || typeof context === 'function') { @@ -37,18 +37,26 @@ export class LoggerService { progress(total: number) { // @todo: see if we can make the progress bar sticky even if other stuff is printed to console - const bar = new cliProgress.SingleBar({ - stopOnComplete: true, - hideCursor: true, - forceRedraw: true, - }, cliProgress.Presets.shades_classic); + const bar = new cliProgress.SingleBar( + { + stopOnComplete: true, + hideCursor: true, + forceRedraw: true, + }, + cliProgress.Presets.shades_classic, + ); bar.start(total, 0); return bar; } - async log(level: string, message: string, meta?: any, options?: LoggerOptionsInterface) { + async log( + level: string, + message: string, + meta?: any, + options?: LoggerOptionsInterface, + ) { const config = this.loggerBuilder.getConfig(); if ( @@ -60,6 +68,9 @@ export class LoggerService { } const logger = this.loggerBuilder.getLogger(); - logger[level](message, { ...meta, context: this.context || LoggerService.name }); + logger[level](message, { + ...meta, + context: this.context || LoggerService.name, + }); } } diff --git a/src/modules/logger/utils/colors.utils.ts b/src/modules/logger/utils/colors.utils.ts index ae33742..ec35656 100644 --- a/src/modules/logger/utils/colors.utils.ts +++ b/src/modules/logger/utils/colors.utils.ts @@ -6,10 +6,20 @@ export class LoggerColorUtils { LoggerColorUtils.isColorAllowed() ? colorFn(text) : text; static clc = { - green: LoggerColorUtils.colorIfAllowed((text: string) => `\x1B[32m${text}\x1B[39m`), - yellow: LoggerColorUtils.colorIfAllowed((text: string) => `\x1B[33m${text}\x1B[39m`), - red: LoggerColorUtils.colorIfAllowed((text: string) => `\x1B[31m${text}\x1B[39m`), - magentaBright: LoggerColorUtils.colorIfAllowed((text: string) => `\x1B[95m${text}\x1B[39m`), - cyanBright: LoggerColorUtils.colorIfAllowed((text: string) => `\x1B[96m${text}\x1B[39m`), + green: LoggerColorUtils.colorIfAllowed( + (text: string) => `\x1B[32m${text}\x1B[39m`, + ), + yellow: LoggerColorUtils.colorIfAllowed( + (text: string) => `\x1B[33m${text}\x1B[39m`, + ), + red: LoggerColorUtils.colorIfAllowed( + (text: string) => `\x1B[31m${text}\x1B[39m`, + ), + magentaBright: LoggerColorUtils.colorIfAllowed( + (text: string) => `\x1B[95m${text}\x1B[39m`, + ), + cyanBright: LoggerColorUtils.colorIfAllowed( + (text: string) => `\x1B[96m${text}\x1B[39m`, + ), }; } diff --git a/src/modules/mailer/mailer.module.ts b/src/modules/mailer/mailer.module.ts index 9e42029..674b198 100644 --- a/src/modules/mailer/mailer.module.ts +++ b/src/modules/mailer/mailer.module.ts @@ -7,15 +7,9 @@ import { ConfigModule } from '../config/config.module'; export const MailerModuleConfig = { imports: [LoggerModule, ConfigModule], controllers: [], - providers: [ - ...mailerProviders, - MailerService, - ], - exports: [ - ...mailerProviders, - MailerService, - ], + providers: [...mailerProviders, MailerService], + exports: [...mailerProviders, MailerService], }; @Module(MailerModuleConfig) -export class MailerModule { } +export class MailerModule {} diff --git a/src/modules/mailer/mailer.providers.ts b/src/modules/mailer/mailer.providers.ts index 306e6a5..82bc799 100644 --- a/src/modules/mailer/mailer.providers.ts +++ b/src/modules/mailer/mailer.providers.ts @@ -1,2 +1 @@ -export const mailerProviders = [ -]; +export const mailerProviders = []; diff --git a/src/modules/mailer/mailer.service.ts b/src/modules/mailer/mailer.service.ts index 7f2c351..f830c5a 100644 --- a/src/modules/mailer/mailer.service.ts +++ b/src/modules/mailer/mailer.service.ts @@ -1,10 +1,10 @@ import { LoggerService } from './../logger/logger.service'; import { ConfigService } from './../config/config.service'; -import { Injectable, OnModuleInit } from '@nestjs/common'; +import { Injectable } from '@nestjs/common'; import nodemailer from 'nodemailer'; @Injectable() -export class MailerService implements OnModuleInit { +export class MailerService { // @note: uses lazyloading: do not use directly, instead use getTransporter() private transporter: nodemailer.Transporter; @@ -12,10 +12,7 @@ export class MailerService implements OnModuleInit { private readonly config: ConfigService, private readonly logger: LoggerService, ) { - this.logger = this.logger.build(MailerService.name) - } - - async onModuleInit() { + this.logger = this.logger.build(MailerService.name); } async getTransporter(): Promise { @@ -29,7 +26,9 @@ export class MailerService implements OnModuleInit { return this.transporter; } - async createAccount(options: nodemailer.TransportOptions): Promise { + async createAccount( + options: nodemailer.TransportOptions, + ): Promise { return nodemailer.createTransport(options); } @@ -42,23 +41,29 @@ export class MailerService implements OnModuleInit { secure: false, auth: { user: testAccount.user, - pass: testAccount.pass - } + pass: testAccount.pass, + }, }); } async sendMail(options: nodemailer.SendMailOptions) { const transporter = await this.getTransporter(); if (!transporter) { - this.logger.debug(`skip sending mail '${options.from}' to '${options.to}'`); + this.logger.debug( + `skip sending mail '${options.from}' to '${options.to}'`, + ); return; } const info = await transporter.sendMail(options); - this.logger.debug(`send mail from '${options.from}' to '${options.to}' got result '${info.response}'`); + this.logger.debug( + `send mail from '${options.from}' to '${options.to}' got result '${info.response}'`, + ); if (this.config.mailer.test) { - this.logger.debug(`sent mail ${info.messageId} ${nodemailer.getTestMessageUrl(info)}`); + this.logger.debug( + `sent mail ${info.messageId} ${nodemailer.getTestMessageUrl(info)}`, + ); } } } diff --git a/src/modules/request/request.module.ts b/src/modules/request/request.module.ts index 43e2996..bc1dc7d 100644 --- a/src/modules/request/request.module.ts +++ b/src/modules/request/request.module.ts @@ -6,21 +6,11 @@ import { ConfigModule } from '../config/config.module'; import { HttpModule } from '@nestjs/axios'; export const RequestModuleConfig = { - imports: [ - LoggerModule, - ConfigModule, - HttpModule - ], + imports: [LoggerModule, ConfigModule, HttpModule], controllers: [], - providers: [ - ...requestProviders, - RequestService, - ], - exports: [ - ...requestProviders, - RequestService, - ], + providers: [...requestProviders, RequestService], + exports: [...requestProviders, RequestService], }; @Module(RequestModuleConfig) -export class RequestModule { } +export class RequestModule {} diff --git a/src/modules/request/request.providers.ts b/src/modules/request/request.providers.ts index ccf4913..0189475 100644 --- a/src/modules/request/request.providers.ts +++ b/src/modules/request/request.providers.ts @@ -1,2 +1 @@ -export const requestProviders = [ -]; +export const requestProviders = []; diff --git a/src/modules/request/request.service.spec.ts b/src/modules/request/request.service.spec.ts index c8515bb..cb6d2e3 100644 --- a/src/modules/request/request.service.spec.ts +++ b/src/modules/request/request.service.spec.ts @@ -11,13 +11,13 @@ describe('RequestService', () => { function spy() { const http = { - request: jest.spyOn(httpService, 'request') - .mockImplementation(() => { - const getPromise = () => new Promise( - resolve => setTimeout(() => resolve({status: 200, body: 'foo'}), 200) + request: jest.spyOn(httpService, 'request').mockImplementation(() => { + const getPromise = () => + new Promise((resolve) => + setTimeout(() => resolve({ status: 200, body: 'foo' }), 200), ); - return from(getPromise()) as Observable; - }), + return from(getPromise()) as Observable; + }), }; return { http }; @@ -44,7 +44,10 @@ describe('RequestService', () => { expect(await requestService.get(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'get', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'get', + url, + }); }); }); @@ -57,7 +60,10 @@ describe('RequestService', () => { expect(await requestService.delete(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'delete', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'delete', + url, + }); }); }); @@ -70,7 +76,10 @@ describe('RequestService', () => { expect(await requestService.head(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'head', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'head', + url, + }); }); }); @@ -83,7 +92,10 @@ describe('RequestService', () => { expect(await requestService.post(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'post', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'post', + url, + }); }); }); @@ -96,7 +108,10 @@ describe('RequestService', () => { expect(await requestService.put(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'put', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'put', + url, + }); }); }); @@ -109,7 +124,10 @@ describe('RequestService', () => { expect(await requestService.patch(url)).toEqual(response); expect(spies.http.request.mock.calls.length).toBe(1); - expect(spies.http.request.mock.calls[0][0]).toEqual({ method: 'patch', url }); + expect(spies.http.request.mock.calls[0][0]).toEqual({ + method: 'patch', + url, + }); }); }); }); diff --git a/src/modules/request/request.service.ts b/src/modules/request/request.service.ts index ed1e312..0a55073 100644 --- a/src/modules/request/request.service.ts +++ b/src/modules/request/request.service.ts @@ -6,12 +6,12 @@ import { HttpService } from '@nestjs/axios'; import { lastValueFrom } from 'rxjs'; @Injectable() -export class RequestService { +export class RequestService { constructor( private readonly http: HttpService, private readonly logger: LoggerService, ) { - this.logger = this.logger.build(RequestService.name) + this.logger = this.logger.build(RequestService.name); } async send(config: RequestOptions): Promise | AxiosError> { @@ -31,39 +31,60 @@ export class RequestService { } } - async get(url: string, config: RequestOptions = {}): Promise | AxiosError> { + async get( + url: string, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'get'; config.url = url; return await this.send(config); } - async delete(url: string, config: RequestOptions = {}): Promise | AxiosError> { + async delete( + url: string, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'delete'; config.url = url; return await this.send(config); } - async head(url: string, config: RequestOptions = {}): Promise | AxiosError> { + async head( + url: string, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'head'; config.url = url; return await this.send(config); } - async post(url: string, data?: any, config: RequestOptions = {}): Promise | AxiosError> { + async post( + url: string, + data?: any, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'post'; config.url = url; config.data = data; return await this.send(config); } - async put(url: string, data?: any, config: RequestOptions = {}): Promise | AxiosError> { + async put( + url: string, + data?: any, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'put'; config.url = url; config.data = data; return await this.send(config); } - async patch(url: string, data?: any, config: RequestOptions = {}): Promise | AxiosError> { + async patch( + url: string, + data?: any, + config: RequestOptions = {}, + ): Promise | AxiosError> { config.method = 'patch'; config.url = url; config.data = data; diff --git a/src/modules/ssl/ssl.middleware.spec.ts b/src/modules/ssl/ssl.middleware.spec.ts index 74b280a..6b54f64 100644 --- a/src/modules/ssl/ssl.middleware.spec.ts +++ b/src/modules/ssl/ssl.middleware.spec.ts @@ -2,14 +2,12 @@ import { Test, TestingModule } from '@nestjs/testing'; import { SSLMiddleware } from './ssl.middleware'; import { SSLService } from './ssl.service'; import { SSLModuleConfig } from './ssl.module'; -import { ConfigService } from '../config/config.service'; import httpMocks from 'node-mocks-http'; describe('SSLMiddleware', () => { let module: TestingModule; let sslMiddleware: SSLMiddleware; let sslService: SSLService; - let configService: ConfigService; beforeEach(async () => { module = await Test.createTestingModule(SSLModuleConfig).compile(); @@ -17,7 +15,6 @@ describe('SSLMiddleware', () => { sslMiddleware = module.get(SSLMiddleware); sslService = module.get(SSLService); - configService = module.get(ConfigService); }); afterEach(() => { diff --git a/src/modules/ssl/ssl.middleware.ts b/src/modules/ssl/ssl.middleware.ts index 64721c4..1f93315 100644 --- a/src/modules/ssl/ssl.middleware.ts +++ b/src/modules/ssl/ssl.middleware.ts @@ -7,12 +7,11 @@ export class SSLMiddleware implements NestMiddleware { constructor(private readonly ssl: SSLService) {} use(req: Request, res: Response, next: NextFunction) { - if (this.ssl.shouldRedirect(req)) { const url = `https://${req.headers.host.replace(/:\d+$/, '')}${req.url}`; res.writeHead(301, { - 'Location': url, + Location: url, 'Content-Type': 'text/html', }); res.end(`You\'re being redirected to ${url}`); diff --git a/src/modules/ssl/ssl.module.ts b/src/modules/ssl/ssl.module.ts index f2144c5..c8b1c89 100644 --- a/src/modules/ssl/ssl.module.ts +++ b/src/modules/ssl/ssl.module.ts @@ -5,19 +5,10 @@ import { Module } from '@nestjs/common'; import { SSLMiddleware } from './ssl.middleware'; export const SSLModuleConfig = { - imports: [ - ConfigModule, - LoggerModule, - ], - providers: [ - SSLMiddleware, - SSLService, - ], - exports: [ - SSLMiddleware, - SSLService, - ], + imports: [ConfigModule, LoggerModule], + providers: [SSLMiddleware, SSLService], + exports: [SSLMiddleware, SSLService], }; @Module(SSLModuleConfig) -export class SSLModule { } +export class SSLModule {} diff --git a/src/modules/ssl/ssl.service.spec.ts b/src/modules/ssl/ssl.service.spec.ts index 8287ddf..0e53687 100644 --- a/src/modules/ssl/ssl.service.spec.ts +++ b/src/modules/ssl/ssl.service.spec.ts @@ -7,15 +7,12 @@ import { ConfigService } from '../config/config.service'; describe('SSLService', () => { let module: TestingModule; let sslService: SSLService; - let configService: ConfigService; beforeEach(async () => { - module = await Test.createTestingModule(SSLModuleConfig) - .compile(); + module = await Test.createTestingModule(SSLModuleConfig).compile(); await module.init(); sslService = module.get(SSLService); - configService = module.get(ConfigService); }); afterEach(async () => { @@ -24,7 +21,9 @@ describe('SSLService', () => { describe('shouldRedirect', () => { it('should return false if ssl is disabled request', () => { - jest.spyOn(ConfigService.prototype, 'ssl', 'get').mockImplementation(() => ({ enabled: false })); + jest + .spyOn(ConfigService.prototype, 'ssl', 'get') + .mockImplementation(() => ({ enabled: false })); const req = httpMocks.createRequest({ hostname: 'example.com', @@ -39,7 +38,9 @@ describe('SSLService', () => { }); it('should return false is hosname is localhost request', () => { - jest.spyOn(ConfigService.prototype, 'ssl', 'get').mockImplementation(() => ({ enabled: true })); + jest + .spyOn(ConfigService.prototype, 'ssl', 'get') + .mockImplementation(() => ({ enabled: true })); const req = httpMocks.createRequest({ hostname: 'localhost', @@ -54,7 +55,9 @@ describe('SSLService', () => { }); it('should return false is path is health endpoint', () => { - jest.spyOn(ConfigService.prototype, 'ssl', 'get').mockImplementation(() => ({ enabled: true })); + jest + .spyOn(ConfigService.prototype, 'ssl', 'get') + .mockImplementation(() => ({ enabled: true })); const req = httpMocks.createRequest({ hostname: 'example.com', @@ -68,8 +71,10 @@ describe('SSLService', () => { expect(sslService.shouldRedirect(req)).toBeFalsy(); }); - it('should return true if it\'s an unsecure and not localhost request', () => { - jest.spyOn(ConfigService.prototype, 'ssl', 'get').mockImplementation(() => ({ enabled: true })); + it("should return true if it's an unsecure and not localhost request", () => { + jest + .spyOn(ConfigService.prototype, 'ssl', 'get') + .mockImplementation(() => ({ enabled: true })); const req = httpMocks.createRequest({ hostname: 'example.com', diff --git a/src/modules/ssl/ssl.service.ts b/src/modules/ssl/ssl.service.ts index 41a291c..c342624 100644 --- a/src/modules/ssl/ssl.service.ts +++ b/src/modules/ssl/ssl.service.ts @@ -4,12 +4,15 @@ import { Request } from 'express'; @Injectable() export class SSLService { - constructor( - private readonly config: ConfigService, - ) {} + constructor(private readonly config: ConfigService) {} public shouldRedirect(req: Request): boolean { - return this.config.ssl.enabled && this.isNotLocal(req) && this.isNotHealthEndpoint(req) && this.isNotSecure(req); + return ( + this.config.ssl.enabled && + this.isNotLocal(req) && + this.isNotHealthEndpoint(req) && + this.isNotSecure(req) + ); } protected isNotHealthEndpoint(req: Request): boolean { diff --git a/src/utils/file-exists.util.ts b/src/utils/file-exists.util.ts index ac235a8..de3b487 100644 --- a/src/utils/file-exists.util.ts +++ b/src/utils/file-exists.util.ts @@ -1,7 +1,8 @@ import fs from 'fs'; export function fileExists(path: string) { - return fs.promises.access(path, fs.constants.F_OK) + return fs.promises + .access(path, fs.constants.F_OK) .then(() => true) .catch(() => false); -}; +} diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.ts index c129c07..db524a4 100644 --- a/test/app.e2e-spec.ts +++ b/test/app.e2e-spec.ts @@ -1,7 +1,11 @@ -import { Test, TestingModule } from '@nestjs/testing'; +import { Test } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import request from 'supertest'; -import { AppModuleConfig, DatabaseService, DB_DEFAULT_CONNECTION } from '../src'; +import { + AppModuleConfig, + DatabaseService, + DB_DEFAULT_CONNECTION, +} from '../src'; describe('Application e2e test', () => { let app: INestApplication; @@ -9,9 +13,14 @@ describe('Application e2e test', () => { beforeAll(async () => { const module = await Test.createTestingModule(AppModuleConfig) .overrideProvider(DB_DEFAULT_CONNECTION) - .useFactory({ factory: (db: DatabaseService) => db.connect(), inject: [DatabaseService] }) + .useFactory({ + factory: (db: DatabaseService) => db.connect(), + inject: [DatabaseService], + }) .compile(); - app = module.createNestApplication(undefined, { logger: ['error', 'warn'] }); + app = module.createNestApplication(undefined, { + logger: ['error', 'warn'], + }); await app.init(); }, 30000); @@ -26,4 +35,4 @@ describe('Application e2e test', () => { expect(res.header.location).toBe('/api'); }); }); -}); \ No newline at end of file +});