-
Notifications
You must be signed in to change notification settings - Fork 182
/
transformers.ts
76 lines (69 loc) · 2.02 KB
/
transformers.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
import type { ValidationOptions } from 'class-validator'
import { Transform, TransformationType } from 'class-transformer'
import { ValidateBy, buildMessage } from 'class-validator'
import { DateTime } from 'luxon'
import { JsonTransformer } from './JsonTransformer'
/**
* Decorator that transforms json to and from corresponding record.
*
* @example
* class Example {
* RecordTransformer(Service)
* private services: Record<string, Service>;
* }
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function RecordTransformer<T>(Class: { new (...args: any[]): T }) {
return Transform(({ value, type }) => {
switch (type) {
case TransformationType.CLASS_TO_PLAIN:
return Object.entries(value).reduce(
(accumulator, [key, attribute]) => ({
...accumulator,
[key]: JsonTransformer.toJSON(attribute),
}),
{}
)
case TransformationType.PLAIN_TO_CLASS:
return Object.entries(value).reduce(
(accumulator, [key, attribute]) => ({
...accumulator,
[key]: JsonTransformer.fromJSON(attribute, Class),
}),
{}
)
default:
return value
}
})
}
/*
* Function that parses date from multiple formats
* including SQL formats.
*/
export function DateParser(value: string): Date {
const parsedDate = new Date(value)
if (parsedDate instanceof Date && !isNaN(parsedDate.getTime())) {
return parsedDate
}
const luxonDate = DateTime.fromSQL(value)
if (luxonDate.isValid) {
return new Date(luxonDate.toString())
}
return new Date()
}
/**
* Checks if a given value is a Map
*/
export function IsMap(validationOptions?: ValidationOptions): PropertyDecorator {
return ValidateBy(
{
name: 'isMap',
validator: {
validate: (value: unknown): boolean => value instanceof Map,
defaultMessage: buildMessage((eachPrefix) => eachPrefix + '$property must be a Map', validationOptions),
},
},
validationOptions
)
}