Last active
August 31, 2021 07:55
-
-
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
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 { 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