Created
February 6, 2023 13:37
-
-
Save Setitch/fce532fc4f70ede2865b788410c5f5e0 to your computer and use it in GitHub Desktop.
NestJS - Transformer for Query params to be transformed into array before validation of dto's (or undefined)
This file contains 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 ToArray = () => { | |
const toPlain = Transform( | |
({value}) => { | |
return value; | |
}, | |
{ | |
toPlainOnly: true, | |
} | |
); | |
const toClass = (target: any, key: string) => { | |
return Transform( | |
({obj}) => { | |
return valueToArray(obj[key]); | |
}, | |
{ | |
toClassOnly: true, | |
} | |
)(target, key); | |
}; | |
return function (target: any, key: string) { | |
toPlain(target, key); | |
toClass(target, key); | |
}; | |
}; | |
const valueToArray = (value: any) => { | |
if (value instanceof Array) return value; | |
if (typeof value === 'string') { | |
if (value === '') return []; | |
return value.split(','); | |
} | |
return undefined; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment