Skip to content

Commit

Permalink
style: lint and format project
Browse files Browse the repository at this point in the history
  • Loading branch information
moesjarraf committed Feb 22, 2023
1 parent 755041a commit 793c4c3
Show file tree
Hide file tree
Showing 46 changed files with 382 additions and 285 deletions.
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 1 addition & 3 deletions src/app/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
5 changes: 1 addition & 4 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('*');
}
}
2 changes: 1 addition & 1 deletion src/app/app.providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ export const commonAppProviders = [
{
provide: APP_FILTER,
useClass: IndexExceptionFilter,
}
},
];
2 changes: 1 addition & 1 deletion src/app/classes/main.class.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
26 changes: 21 additions & 5 deletions src/common.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
10 changes: 8 additions & 2 deletions src/filters/common-exception.filter.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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) {
Expand Down
7 changes: 2 additions & 5 deletions src/filters/exception.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -27,4 +24,4 @@ export const ExceptionModuleConfig = {
};

@Module(ExceptionModuleConfig)
export class ExceptionModule { }
export class ExceptionModule {}
53 changes: 32 additions & 21 deletions src/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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) {
Expand All @@ -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,
});
}
}
15 changes: 13 additions & 2 deletions src/filters/index-exception.filter.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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);
}

Expand Down
46 changes: 28 additions & 18 deletions src/filters/internal-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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) {
Expand All @@ -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,
});
}
}
14 changes: 9 additions & 5 deletions src/modules/captcha/captcha.guard.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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;
}

}
14 changes: 8 additions & 6 deletions src/modules/captcha/captcha.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
2 changes: 1 addition & 1 deletion src/modules/captcha/captcha.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ export const CaptchaModuleConfig = {
};

@Module(CaptchaModuleConfig)
export class CaptchaModule { }
export class CaptchaModule {}
6 changes: 0 additions & 6 deletions src/modules/captcha/captcha.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,8 @@ import { RECAPTCHA } from '../../constants';
describe('CaptchaService', () => {
let module: TestingModule;
let captchaService: CaptchaService;
let spies: ReturnType<typeof spy>;
let providers: ReturnType<typeof provide>;

function spy() {
return {};
}

function provide() {
const captchaInstance = jest.fn();
const recaptcha = jest.fn(() => captchaInstance);
Expand All @@ -30,7 +25,6 @@ describe('CaptchaService', () => {
await module.init();

captchaService = module.get<CaptchaService>(CaptchaService);
spies = spy();
});

afterEach(async () => {
Expand Down
Loading

0 comments on commit 793c4c3

Please sign in to comment.