Created
February 6, 2023 13:43
-
-
Save Setitch/61b2bc42dc4d3ca7678eb5083b319aae to your computer and use it in GitHub Desktop.
NestJS - Transformer for Query params to be transformed into Integer before validation of dto's (or undefined)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Transform } from 'class-transformer'; | |
| export const ToInteger = () => { | |
| const toPlain = Transform( | |
| ({value}) => { | |
| return value; | |
| }, | |
| { | |
| toPlainOnly: true, | |
| } | |
| ); | |
| const toClass = (target: any, key: string) => { | |
| return Transform( | |
| ({obj}) => { | |
| return valueToInteger(obj[key]); | |
| }, | |
| { | |
| toClassOnly: true, | |
| } | |
| )(target, key); | |
| }; | |
| return function (target: any, key: string) { | |
| toPlain(target, key); | |
| toClass(target, key); | |
| }; | |
| }; | |
| const valueToInteger = (value: any) => { | |
| if (value === null || value === undefined) { | |
| return undefined; | |
| } | |
| if (typeof value === 'number') { | |
| return Number.isInteger(value) ? value : value.toFixed(0); | |
| } | |
| if (!(value.toString())) return undefined; | |
| return Number.parseInt(value.toString(), 10); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment