DEV Community

Cover image for Nestjs x ExpressoTS @param transformation
Richard Zampieri for ExpressoTS

Posted on

Nestjs x ExpressoTS @param transformation

The ExpressoTS Adapter provides essential resources for the Express.js platform, including decorators. We've recently released an enhancement to the adapter that addresses a subtle but critical issue you might not notice until it becomes a problem.

In TypeScript, parameters from URL paths (e.g., :id in Express.js routes) are passed as strings, even if they represent numbers. This behavior is standard across many web frameworks, including Express.js.

Here’s how you typically handle this in your code:

// Controller
@Get("/:id")
    findOne(@param("id") id: number) {
        return this.userUseCase.findOne(Number(id));
    }

// Use Case
findOne(id: number) {
        return this.db.users.find((user) => user.id === id);
    }

// DB
const users = [
        {
            id: 1,
            name: "Alice Smith",
            email: "alice@example.com",
            role: "Admin",
        },
        {
            id: 2,
            name: "Bob Johnson",
            email: "bob@example.com",
            role: "Regular",
        }
]
Enter fullscreen mode Exit fullscreen mode

Directly comparing the id from the request without converting it to a number can lead to unexpected results due to type mismatches.

In contrast, NestJS uses Binding Pipes to handle this conversion. This method involves passing data through multiple layers for conversion, requiring developers to be familiar with the necessary pipes.

.NET Core simplifies this process by using annotations to automatically convert types based on the variable receiving the parameter.

At ExpressoTS, we've streamlined this process even further. Our @param decorator not only converts the parameter but also validates it against the expected type of the receiving variable. This approach enhances efficiency and intuitiveness. Here's how it looks:

@Get("/:id")
    findOne(@param("id") id: number) {
        return this.userUseCase.findOne(id);
    }
Enter fullscreen mode Exit fullscreen mode

The id parameter is automatically converted from a string to a number, eliminating the common error of undefined results when comparing different types and you don't need to memorize pipes to convert your parameter to the desired type, that should work out-of-the box.

Top comments (0)