-
Notifications
You must be signed in to change notification settings - Fork 1
/
create-order-item.dto.ts
96 lines (85 loc) · 2.6 KB
/
create-order-item.dto.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
ArrayMinSize,
IsArray,
IsEnum,
IsNotEmpty,
IsOptional,
IsString,
registerDecorator,
ValidateNested,
ValidationOptions
} from "class-validator";
import { Countries } from "@energyweb/utils-general";
import { CreateOrderItemTimeframeDto } from "./create-order-item-timeframe.dto";
import { Type } from "class-transformer";
export class CreateOrderItemDto {
@ApiProperty({ example: "PL" })
@IsEnum(Countries.map(i => i.code))
country: string;
@ApiPropertyOptional({ example: "Kraków" })
@IsString()
@IsOptional()
city: string;
@ApiProperty({ example: "1234" })
@IsString()
@IsNotEmpty()
minerId: string;
@ApiProperty({ type: [CreateOrderItemTimeframeDto] })
@IsArray()
@ArrayMinSize(1)
@Type(() => CreateOrderItemTimeframeDto)
@ValidateNested()
@TimeframesInSequence({ message: "timeFrames items start values need to be sorted chronologically" })
@AdjacentTimeframes({ message: "timeFrame items should be adjacent" })
timeFrames: CreateOrderItemTimeframeDto[];
}
function TimeframesInSequence(validationOptions?: ValidationOptions) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: "TimeframesInSequence",
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: {
validate(value: any) {
if (value.length < 2) {
return true;
}
for (let i = 0; i < value.length - 1; i++) {
if (value[i].start >= value[i + 1].start) {
return false;
}
}
return true;
}
}
});
};
}
function AdjacentTimeframes(validationOptions?: ValidationOptions) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: "AdjacentTimeframes",
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: {
validate(value: Array<{start: string | number | Date, end: string | number | Date}>): boolean {
if (value.length < 2) {
return true;
}
for (let i = 0; i < value.length - 1; i++) {
const nextStartDate = new Date(value[i + 1].start);
const endDate = new Date(value[i].end);
if (Math.abs(nextStartDate.getTime() - endDate.getTime()) !== 1) {
return false;
}
}
return true;
}
}
});
};
}