Skip to content

Commit

Permalink
Merge pull request #18 from gobeam/fix/validation
Browse files Browse the repository at this point in the history
fix: validation issue fixed
  • Loading branch information
gobeam committed Aug 1, 2022
2 parents a3fc167 + 200ddef commit 374ab98
Show file tree
Hide file tree
Showing 16 changed files with 373 additions and 179 deletions.
48 changes: 48 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Continuous Integration Testing

on: push

jobs:
unit-tests:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
test: [truthy-cms]

steps:
- uses: actions/checkout@v2
- name: Use NodeJS ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Install dependencies
run: npm install

- name: Run unit test
run: npm run test:unit

e2e-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
needs: [unit-tests]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Set Environment Variables
uses: ./.github/actions/setvars
with:
varFilePath: ./.github/variables/myvars.env
- name: Start Docker-Compose
run: docker-compose -f docker-compose-test.yml up -d
- name: Install dependencies
run: npm install
- name: Run tests
run: npm run test:e2e
- name: Stop Docker-Compose
run: docker-compose -f docker-compose-test.yml down
52 changes: 0 additions & 52 deletions .github/workflows/test.yml

This file was deleted.

15 changes: 15 additions & 0 deletions docker-compose-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: '3'
services:
truthy-postgres:
image: postgres
ports:
- '5432:5432'
environment:
- POSTGRES_USER=truthy_user
- POSTGRES_PASSWORD=truthypwd
- POSTGRES_DB=truthy_db

redis:
image: redis
ports:
- '6379:6379'
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,20 @@
"test:watch": "jest --config ./test/unit/jest-unit.json --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/e2e/jest-e2e.json --runInBand --detectOpenHandles",
"test:unit": "jest --config ./test/unit/jest-unit.json --runInBand",
"test:e2e": "NODE_ENV=test jest --config ./test/e2e/jest-e2e.json --runInBand --detectOpenHandles",
"test:unit": "NODE_ENV=test jest --config ./test/unit/jest-unit.json --runInBand",
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/ormconfig.ts",
"orm-create": "npm run typeorm migration:create -- -n",
"migrate": "npm run typeorm migration:run",
"migration:rollback": "npm run typeorm migration:revert",
"seed": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js seed -n src/config/ormconfig.ts",
"precommit": "lint-staged && npm run lint && npm run test:unit && npm run test:e2e",
"precommit": "lint-staged && npm run lint",
"prepush": "npm run test:unit && npm run test:e2e",
"prepare": "husky install"
},
"dependencies": {
"@aws-sdk/client-cloudwatch-logs": "^3.54.1",
"@faker-js/faker": "^6.0.0",
"@nestjs-modules/mailer": "^1.6.1",
"@nestjs/bull": "^0.5.3",
"@nestjs/common": "^8.4.1",
Expand Down
2 changes: 1 addition & 1 deletion src/common/pipes/custom-validation.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class CustomValidationPipe implements PipeTransform<any> {
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
if (errors && errors.length > 0) {
const translatedError = await this.transformError(errors);
throw new UnprocessableEntityException(translatedError);
}
Expand Down
114 changes: 69 additions & 45 deletions src/common/pipes/i18n-exception-filter.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,22 @@ import {
Catch,
ExceptionFilter,
HttpException,
HttpStatus
HttpStatus,
Inject
} from '@nestjs/common';
import { I18nService } from 'nestjs-i18n';

import { ValidationErrorInterface } from 'src/common/interfaces/validation-error.interface';
import { StatusCodesList } from 'src/common/constants/status-codes-list.constants';
import { Logger } from 'winston';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';

@Catch(HttpException)
export class I18nExceptionFilterPipe implements ExceptionFilter {
constructor(private readonly i18n: I18nService) {}
constructor(
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
private readonly i18n: I18nService
) {}

async catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
Expand All @@ -28,49 +34,57 @@ export class I18nExceptionFilterPipe implements ExceptionFilter {
}

async getMessage(exception: HttpException, lang: string) {
const exceptionResponse = exception.getResponse() as any;
if (!exceptionResponse.message && typeof exceptionResponse === 'string') {
return await this.i18n.translate(`exception.${exceptionResponse}`, {
lang,
args: {}
});
}
if (exceptionResponse.statusCode === HttpStatus.UNPROCESSABLE_ENTITY) {
if (
exceptionResponse.hasOwnProperty('message') &&
exceptionResponse.message instanceof Array
try {
const exceptionResponse = exception.getResponse() as any;
if (!exceptionResponse.message && typeof exceptionResponse === 'string') {
return await this.i18n.translate(`exception.${exceptionResponse}`, {
lang,
args: {}
});
}
if (exceptionResponse.statusCode === HttpStatus.UNPROCESSABLE_ENTITY) {
if (
exceptionResponse.hasOwnProperty('message') &&
exceptionResponse.message instanceof Array
) {
exceptionResponse.code = StatusCodesList.ValidationError;
exceptionResponse.message = await this.translateArray(
exceptionResponse.message,
lang
);
}
return exceptionResponse;
}
let errorMessage = 'internalError';
if (exceptionResponse.message instanceof Array) {
errorMessage = exceptionResponse.message[0];
} else if (typeof exceptionResponse.message === 'string') {
errorMessage = exceptionResponse.message;
} else if (
!exceptionResponse.message &&
typeof exceptionResponse === 'string'
) {
exceptionResponse.code = StatusCodesList.ValidationError;
exceptionResponse.message = await this.translateArray(
exceptionResponse.message,
lang
);
errorMessage = exceptionResponse;
}
return exceptionResponse;
}
let errorMessage = 'internalError';
if (exceptionResponse.message instanceof Array) {
errorMessage = exceptionResponse.message[0];
} else if (typeof exceptionResponse.message === 'string') {
errorMessage = exceptionResponse.message;
} else if (
!exceptionResponse.message &&
typeof exceptionResponse === 'string'
) {
errorMessage = exceptionResponse;
}

const { title, argument } = this.checkIfConstraintAvailable(errorMessage);
exceptionResponse.message = await this.i18n.translate(
`exception.${title}`,
{
lang,
args: {
...argument
const { title, argument } = this.checkIfConstraintAvailable(errorMessage);
exceptionResponse.message = await this.i18n.translate(
`exception.${title}`,
{
lang,
args: {
...argument
}
}
}
);
return exceptionResponse;
);
return exceptionResponse;
} catch (error) {
this.logger.error('Error in I18nExceptionFilterPipe: ', {
meta: {
error
}
});
}
}

checkIfConstraintAvailable(message: string): {
Expand Down Expand Up @@ -106,7 +120,8 @@ export class I18nExceptionFilterPipe implements ExceptionFilter {
'isIn',
'matches',
'maxLength',
'minLength'
'minLength',
'isLength'
];
const item = errors[i];
let message = [];
Expand All @@ -122,13 +137,22 @@ export class I18nExceptionFilterPipe implements ExceptionFilter {
validationKey = title;
validationArgument = argument;
}
return this.i18n.translate(`validation.${validationKey}`, {
const args: Record<string, any> = {
lang,
args: {
...validationArgument,
property: item.property
}
});
};
if (
validationArgument &&
Object.keys(validationArgument).length > 0
) {
args.args = {
...validationArgument,
property: item.property
};
}
return this.i18n.translate(`validation.${validationKey}`, args);
})
);
}
Expand Down
6 changes: 5 additions & 1 deletion src/config/ormconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ const ormConfig: ConnectionOptions = {
database: process.env.DB_DATABASE_NAME || dbConfig.database,
migrationsTransactionMode: 'each',
entities: [__dirname + '/../**/*.entity.{js,ts}'],
synchronize: process.env.TYPE_ORM_SYNC || dbConfig.synchronize,
logging: false,
synchronize: false,
migrationsRun: process.env.NODE_ENV === 'test',
dropSchema: process.env.NODE_ENV === 'test',
migrationsTableName: 'migrations',
migrations: [__dirname + '/../database/migrations/**/*{.ts,.js}'],
cli: {
migrationsDir: 'src/database/migrations'
Expand Down
18 changes: 15 additions & 3 deletions src/refresh-token/entities/refresh-token.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import {
BaseEntity,
Column,
Entity,
Index,
PrimaryGeneratedColumn
} from 'typeorm';

@Entity({
name: 'refresh_token'
Expand All @@ -16,10 +22,16 @@ export class RefreshToken extends BaseEntity {
@Column()
userAgent: string;

@Column()
@Index()
@Column({
nullable: true
})
browser: string;

@Column()
@Index()
@Column({
nullable: true
})
os: string;

@Column()
Expand Down
3 changes: 2 additions & 1 deletion test/e2e/app/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ describe('AppController (e2e)', () => {
let app: AppFactory;

beforeAll(async () => {
await AppFactory.dropTables();
app = await AppFactory.new();
});

beforeEach(async () => {
await app.refreshDatabase();
await AppFactory.cleanupDB();
});

it('/ (GET)', () => {
Expand Down
Loading

0 comments on commit 374ab98

Please sign in to comment.