Skip to content

Instantly share code, notes, and snippets.

@Setitch
Created February 6, 2023 13:37
Show Gist options
  • Save Setitch/fce532fc4f70ede2865b788410c5f5e0 to your computer and use it in GitHub Desktop.
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)
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