nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.69k stars 7.63k forks source link

Params decorator always returns undefined #1362

Closed ErikMartensson closed 5 years ago

ErikMartensson commented 5 years ago

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

The param decorator, in my controller, is always returning undefined. I get the same result even if I try to pick out a specific parameter, like in the tutorial. The route itself works fine. I can add a POST route too with no problem.

Expected behavior

I was hoping for an object, where the only property inside would be the id parameter from the route. Alternatively, picking out a specific route parameter would extract that one only, but it doesn't work either. Like so:

@Get(':id')
findOne(@Param('id') id) {
    return `This action returns a #${id} cat`;
}

Minimal reproduction of the problem with instructions

I've been following the tutorial here down to the section about "Route parameters".

import { Controller, Get } from '@nestjs/common'

@Controller('cats')
export class CatController {
    @Get(':id')
    findOne(@Param() params) {
        console.log(params) // <- Always logs undefined for me
        return 'This action returns all cats'
    }
}

Environment


Nest version: 5.0.1

For Tooling issues:
- Node version: 11.4.0
--
- Platform: Docker container with image `node:alpine`

Others:
NPM version: 6.4.1
Pure JavaScript, cloned from the `javascript-starter` repo.
ErikMartensson commented 5 years ago

As it turns out, I didn't read the documentation carefully enough. A colleague of mine figured out that the example I was following is currently only supported in TypeScript and that Babel for now doesn't support decorators in function parameters (no, not even with the transform-function-parameter-decorators plugin).

So this is what solved it, binding the Param decorator to my method with the Bind decorator.

import { Controller, Bind, Get, Param } from '@nestjs/common'

@Controller('cats')
export class CatController {
    @Get(':id')
    @Bind(Param())
    findOne(params) {
        console.log(params) // <- Logs my parameters now
        return 'This action returns all cats'
    }
}
lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.