Skip to content

Instantly share code, notes, and snippets.

@Setitch
Created February 6, 2023 13:43
Show Gist options
  • Select an option

  • Save Setitch/61b2bc42dc4d3ca7678eb5083b319aae to your computer and use it in GitHub Desktop.

Select an option

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)
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