adding punctual or reccurent validator

This commit is contained in:
Grégoire Chevalier 2023-05-25 15:43:23 +02:00
parent e2e3bd4407
commit 6839e81cd6
8 changed files with 168 additions and 39 deletions

View File

@ -21,8 +21,8 @@
"test:unit": "jest --testPathPattern 'tests/unit/' --verbose", "test:unit": "jest --testPathPattern 'tests/unit/' --verbose",
"test:unit:watch": "jest --testPathPattern 'tests/unit/' --verbose --watch", "test:unit:watch": "jest --testPathPattern 'tests/unit/' --verbose --watch",
"test:unit:ci": "jest --testPathPattern 'tests/unit/' --coverage", "test:unit:ci": "jest --testPathPattern 'tests/unit/' --coverage",
"test:integration": "npm run migrate:test && dotenv -e .env.test -- jest --testPathPattern 'tests/integration/' --verbose --watch", "test:integration": "npm run migrate:test && dotenv -e .env.test -- jest --testPathPattern 'tests/integration/' --verbose",
"test:integration:watch": "npm run migrate:test && dotenv -e .env.test -- jest --testPathPattern 'tests/integration/' --verbose", "test:integration:watch": "npm run migrate:test && dotenv -e .env.test -- jest --testPathPattern 'tests/integration/' --verbose --watch",
"test:integration:ci": "npm run migrate:test:ci && dotenv -e ci/.env.ci -- jest --testPathPattern 'tests/integration/'", "test:integration:ci": "npm run migrate:test:ci && dotenv -e ci/.env.ci -- jest --testPathPattern 'tests/integration/'",
"test:cov": "jest --testPathPattern 'tests/unit/' --coverage", "test:cov": "jest --testPathPattern 'tests/unit/' --coverage",
"test:e2e": "jest --config ./test/jest-e2e.json", "test:e2e": "jest --config ./test/jest-e2e.json",

View File

@ -41,6 +41,8 @@ export class AdController {
@GrpcMethod('AdsService', 'Create') @GrpcMethod('AdsService', 'Create')
async createAd(data: CreateAdRequest): Promise<AdPresenter> { async createAd(data: CreateAdRequest): Promise<AdPresenter> {
console.log('controler');
console.log(data);
try { try {
const ad = await this._commandBus.execute(new CreateAdCommand(data)); const ad = await this._commandBus.execute(new CreateAdCommand(data));
return this._mapper.map(ad, Ad, AdPresenter); return this._mapper.map(ad, Ad, AdPresenter);

View File

@ -20,6 +20,7 @@ import { AddressRequestDTO } from './create.address.request';
import { HasProperPassengerSeats } from './validators/has-passenger-seats.validator'; import { HasProperPassengerSeats } from './validators/has-passenger-seats.validator';
import { HasProperDriverSeats } from './validators/has-driver-seats.validator'; import { HasProperDriverSeats } from './validators/has-driver-seats.validator';
import { HasProperPositionIndexes } from './validators/address-position.validator'; import { HasProperPositionIndexes } from './validators/address-position.validator';
import { IsPunctualOrRecurrent } from './validators/is-punctual-or-recurrent.validator';
export class CreateAdRequest { export class CreateAdRequest {
@IsOptional() @IsOptional()
@ -48,28 +49,30 @@ export class CreateAdRequest {
@AutoMap() @AutoMap()
frequency: Frequency; frequency: Frequency;
@ValidateIf((ad) => ad.frequency === 'PUNCTUAL') @IsOptional()
@IsPunctualOrRecurrent()
@Type(() => Date) @Type(() => Date)
@IsDate() @IsDate()
@AutoMap() @AutoMap()
departure?: Date; departure?: Date;
@ValidateIf((ad) => ad.frequency === 'RECURRENT') @IsOptional()
@IsPunctualOrRecurrent()
@Type(() => Date) @Type(() => Date)
@IsDate() @IsDate()
@AutoMap() @AutoMap()
fromDate?: Date; fromDate?: Date;
@ValidateIf((ad) => ad.frequency === 'RECURRENT') @IsOptional()
@IsPunctualOrRecurrent()
@Type(() => Date) @Type(() => Date)
@IsDate() @IsDate()
@AutoMap() @AutoMap()
toDate?: Date; toDate?: Date;
@ValidateIf((ad) => ad.frequency === 'RECURRENT')
@Type(() => ScheduleDTO) @Type(() => ScheduleDTO)
@IsPunctualOrRecurrent()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@IsNotEmptyObject()
@AutoMap() @AutoMap()
schedule: ScheduleDTO = {}; schedule: ScheduleDTO = {};

View File

@ -4,35 +4,53 @@ import {
ValidationOptions, ValidationOptions,
buildMessage, buildMessage,
} from 'class-validator'; } from 'class-validator';
import { Frequency } from '../../types/frequency.enum';
function isPunctual(): boolean { function isPunctual(args: ValidationArguments): boolean {
throw new Error('Function not implemented.'); if (
args.object['frequency'] === Frequency.PUNCTUAL &&
args.object['departure'] instanceof Date &&
!Object.keys(args.object['schedule']).length
)
return true;
return false;
} }
function isRecurrent(): boolean { function isRecurrent(args: ValidationArguments): boolean {
throw new Error('Function not implemented.'); if (
args.object['frequency'] === Frequency.RECURRENT &&
args.object['fromDate'] instanceof Date &&
args.object['toDate'] instanceof Date &&
Object.keys(args.object['schedule']).length
)
return true;
return false;
} }
export const isPunctualOrRecurrent = (): boolean => { export const isPunctualOrRecurrent = (args: ValidationArguments): boolean => {
return isPunctual() || isRecurrent(); console.log('validator ');
console.log(args.object);
return isPunctual(args) || isRecurrent(args);
}; };
/* istanbul ignore next */ /* istanbul ignore next */
// export function IsPunctualOrRecurrent( export function IsPunctualOrRecurrent(
// validationOptions?: ValidationOptions, validationOptions?: ValidationOptions,
// ): PropertyDecorator { ): PropertyDecorator {
// return ValidateBy( return ValidateBy(
// { {
// name: '', name: '',
// constraints: [], constraints: [],
// validator: { validator: {
// validate: (value, args: ValidationArguments): boolean => validate: (value, args: ValidationArguments): boolean =>
// isPunctualOrRecurrent(value, args), isPunctualOrRecurrent(args),
// defaultMessage: buildMessage( defaultMessage: buildMessage(
// () => `driver and driver seats are not correct`, () =>
// validationOptions, `the departure, from date, to date and schedule must be properly set on reccurent or punctual ad `,
// ), validationOptions,
// }, ),
// }, },
// validationOptions, },
// ); validationOptions,
// } );
}

View File

@ -3,11 +3,7 @@ import { CreateAdRequest } from '../dtos/create-ad.request';
import { Frequency } from '../types/frequency.enum'; import { Frequency } from '../types/frequency.enum';
export class RecurrentNormaliser { export class RecurrentNormaliser {
constructor() {
console.log('resolver call');
}
fromDateResolver(createAdRequest: CreateAdRequest): Date { fromDateResolver(createAdRequest: CreateAdRequest): Date {
console.log('resolver call');
if (createAdRequest.frequency === Frequency.PUNCTUAL) if (createAdRequest.frequency === Frequency.PUNCTUAL)
return createAdRequest.departure; return createAdRequest.departure;
return createAdRequest.fromDate; return createAdRequest.fromDate;

View File

@ -27,8 +27,6 @@ export class CreateAdUseCase {
} }
async execute(command: CreateAdCommand): Promise<Ad> { async execute(command: CreateAdCommand): Promise<Ad> {
console.log('usecase');
console.log(command.createAdRequest);
this.ad = this._mapper.map( this.ad = this._mapper.map(
command.createAdRequest, command.createAdRequest,
CreateAdRequest, CreateAdRequest,

View File

@ -0,0 +1,113 @@
import { isPunctualOrRecurrent } from '../../../domain/dtos/validators/is-punctual-or-recurrent.validator';
import { Frequency } from '../../../domain/types/frequency.enum';
describe('punctual or reccurent validators', () => {
describe('punctual case ', () => {
describe('valid cases', () => {
it('should validate with valid departure and empty schedule ', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.PUNCTUAL,
departure: new Date('01-02-2023'),
schedule: {},
},
property: '',
}),
).toBeTruthy();
});
});
describe('invalid cases ', () => {
it('should not validate with invalid departure and empty schedule and margin', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.PUNCTUAL,
fromDate: new Date('20-10-2023'),
toDate: new Date('30-10-2023'),
},
property: '',
}),
).toBeFalsy();
});
it('should not validate with no empty schedule', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.PUNCTUAL,
departure: new Date('01-02-2023'),
schedule: {
mon: '08:30',
},
},
property: '',
}),
).toBeFalsy();
});
});
});
describe('reccurent case ', () => {
describe('valid cases', () => {
it('should validate with valid from date, to date and non empty schedule ', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.RECURRENT,
fromDate: new Date('01-15-2023'),
toDate: new Date('06-30-2023'),
schedule: {
mon: '08:30',
},
},
property: '',
}),
).toBeTruthy();
});
});
describe('invalid cases ', () => {
it('should not validate with empty schedule ', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.RECURRENT,
fromDate: new Date('01-15-2023'),
toDate: new Date('06-30-2023'),
schedule: {},
},
property: '',
}),
).toBeFalsy();
});
it('should not validate with invalid from date to date and empty schedule and margin', () => {
expect(
isPunctualOrRecurrent({
value: undefined,
constraints: [],
targetName: '',
object: {
frequency: Frequency.RECURRENT,
departure: new Date('20-10-2023'),
toDate: new Date('30-10-2023'),
},
property: '',
}),
).toBeFalsy();
});
});
});
});

View File

@ -87,7 +87,6 @@ export abstract class PrismaRepository<T> implements IRepository<T> {
}); });
return res; return res;
} catch (e) { } catch (e) {
console.log(e);
if (e instanceof Prisma.PrismaClientKnownRequestError) { if (e instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseException( throw new DatabaseException(
Prisma.PrismaClientKnownRequestError.name, Prisma.PrismaClientKnownRequestError.name,