Better cron validation

This commit is contained in:
Gabriel Rosa
2022-05-31 16:10:21 -03:00
parent ae069a0e00
commit 329bbf2e4d
3 changed files with 1350 additions and 1483 deletions
+1333 -1475
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -44,7 +44,7 @@
"swagger-ui-express": "^4.3.0"
},
"overrides": {
"busboy@<1.6.0": "^1.6.0"
"multer": "1.4.5-lts.1"
},
"devDependencies": {
"@nestjs/cli": "^8.2.4",
+16 -7
View File
@@ -1,6 +1,6 @@
import { Body, HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Timeout } from '@nestjs/schedule';
import CronParser from 'cron-parser';
import CronParser, { CronExpression } from 'cron-parser';
import { InputsClientService } from 'src/clients/inputs/client.service';
import { IIdRequest, Info } from 'src/clients/inputs/interfaces';
@@ -13,25 +13,34 @@ export class InputsService {
adjustInputPayload(payload) {
return payload?.input_s3 || payload?.input_jdbc;
}
getDifferenceInSeconds(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
getDifferenceInSeconds(date1: Date, date2: Date) {
const diffInMs = Math.abs(date2.getTime() - date1.getTime());
return diffInMs / 1000;
}
validateCron(data) {
const { info, cron } = data;
const { customer_tier } = info;
const interval = CronParser.parseExpression(cron);
if (!cron) return;
let interval: CronExpression;
try {
interval = CronParser.parseExpression(cron);
} catch (error) {
throw new HttpException(
'Intervalo de tempo inválido',
HttpStatus.BAD_REQUEST,
);
}
const nextDate = interval.next().toDate();
const afterNextDate = interval.next().toDate();
const secondsApart = this.getDifferenceInSeconds(nextDate, afterNextDate);
if (customer_tier === 'BASIC' && secondsApart < this.secondsInADay) {
throw new HttpException(
'Não é possível criar um input com intervalo de tempo menor do que um dia.',
'Intervalo de tempo não pode ser inferior a um dia.',
HttpStatus.FORBIDDEN,
);
} else if (secondsApart < this.secondsInAnHour) {
throw new HttpException(
'Não é possível criar um input com intervalo de tempo menor do que uma hora.',
'Intervalo de tempo não pode ser inferior a uma hora.',
HttpStatus.FORBIDDEN,
);
}
@@ -92,7 +101,7 @@ export class InputsService {
}
async update(id: string, data, info: Info) {
this.validateCron(data);
this.validateCron({ ...data, info });
try {
const updateInputResponse: any = await this.inputClient.update({
id,