Pipe para validar RUT en NestJS

rut.pipe.ts
1
import { BadRequestException, PipeTransform } from "@nestjs/common";
2
3
export class isRutValid implements PipeTransform {
4
async transform(value: any) {
5
if (!value) {
6
throw new BadRequestException("RUT is required");
7
}
8
9
if (!value.match(/^[0-9]+[-]{1}[0-9kK]{1}$/)) {
10
throw new BadRequestException(
11
"RUT have invalid format, must be 12345678-9",
12
);
13
}
14
15
return value;
16
}
17
}

Modo de uso:

test.controller.ts
1
import { Controller, Get, Header, Query } from "@nestjs/common";
2
import { isRutValid } from "./rut.pipe";
3
4
@Controller()
5
export class TestController {
6
@Get("test-rut")
7
@Header("content-type", "application/json")
8
testRut(
9
@Query("rut", isRutValid)
10
rut: string,
11
): any {
12
return rut;
13
}
14
}

resultado:

curl http://localhost:8080/test-rut?rut=invalid_rut

{
"message": "RUT have invalid format, must be 12345678-9",
"error": "Bad Request",
"statusCode": 400
}