Reputation: 109
How is the elegant way to handle non standard HTTP methods like COPY, LINK, LOCK, UNLOCK in NestJs Controller?
For standard HTTP Methods Request such GET, POST, PUT... We have a decorator like @Get, @Post, etc. But i want to handle some requests with LOCK, UNLOCK and some others... in an elegant way....
I Try to use @All decorator, but i think its not ideal...
I Lookig for something like:
@COPY('auth/copy-user-rights')
async copy_user_rights(): Promise<... {
......
}
Upvotes: 0
Views: 499
Reputation: 109
I know its not elegant, buts....
My Workaround
@All('assign-except-claim')
async assign_except_claim(@Req() req: Request) {
switch (req.method) {
case 'LINK':
...
break;
case 'UNLINK':
...
break;
default:
throw new NotFoundException();
break;
}
}
Upvotes: 1
Reputation: 70211
You can make use of the @RequestMapping()
decorator and manually apply the path and method, and tell Typescript to ignore the error. It seems to work on a minimum reproduction
@RequestMapping({ path: 'copy', method: 'COPY' as any })
copyPath() {
console.log('called copy path');
return this.appService.getHello();
}
Startup logs
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [NestFactory] Starting Nest application...
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [InstanceLoader] AppModule dependencies initialized +10ms
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [RoutesResolver] AppController {/}: +5ms
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [RouterExplorer] Mapped {/copy, undefined} route +1ms
[Nest] 3501141 - 02/20/2023, 11:58:28 AM LOG [NestApplication] Nest application successfully started +1ms
called copy path
curl
curl -X COPY http://localhost:3000/copy -v
* Trying 127.0.0.1:3000...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> COPY /copy HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.86.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 12
< ETag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"
< Date: Mon, 20 Feb 2023 19:58:34 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
* Connection #0 to host localhost left intact
Hello World!
Upvotes: 0