Skip to content

Instantly share code, notes, and snippets.

@adelin-b
Last active August 31, 2021 07:55
Show Gist options
  • Save adelin-b/9842823e4fd72f1b269d11ff19276313 to your computer and use it in GitHub Desktop.
Save adelin-b/9842823e4fd72f1b269d11ff19276313 to your computer and use it in GitHub Desktop.
Nest js pipe to transform query string boolean into boolean using open api metadata
import { PipeTransform, Injectable, ArgumentMetadata } from "@nestjs/common";
type TrueArgumentMetadata = ArgumentMetadata & {
metatype: { _OPENAPI_METADATA_FACTORY: () => Record<string, any> };
};
@Injectable()
export class TransformBooleanPipe implements PipeTransform<any> {
transform(value: any, { metatype }: TrueArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const openApiMetadata = metatype._OPENAPI_METADATA_FACTORY();
Object.keys(value).forEach(key => {
if (
typeof openApiMetadata?.[key]?.type()() === "boolean" &&
typeof value[key] === "string"
) {
value[key] = value[key] === "true";
}
});
return value;
}
// eslint-disable-next-line @typescript-eslint/ban-types
private toValidate(metatype: Function): boolean {
// eslint-disable-next-line @typescript-eslint/ban-types
const types: Function[] = [Boolean];
return !types.includes(metatype);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment