question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Parse controller method argument into Entity

See original GitHub issue

Hello! I think a much needed feature is to automatically parse Controller method arguments into the appropriate Entity. This is very easy to do using a pipe, but I think it is worth making its own example, or even an npm package, so that it can be plugged in effortlessly.

import { HttpException } from '@nestjs/core';
import { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Pipe()
export default class EntityParserPipe implements PipeTransform<any> {
    async transform(value, metadata: ArgumentMetadata) {
      const { metatype } = metadata;
      if (!metatype || !this.toValidate(metatype)) {
          return value;
      }
      const entity = plainToClass(metatype, value);
      const errors = await validate(entity);
      if (errors.length > 0) {
          throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST);
      }
      return entity;
    }

    private toValidate(metatype): boolean {
      const types = [String, Boolean, Number, Array, Object];
      return !types.find((type) => metatype === type);
    }
}

This is what I’m using, and you’ll notice its almost exactly the same as the validation example from the pipe tutorial. Therefore, I don’t want to post this on npm and claim credit. Could I commit it to the core repo? Again, I know this is an easy feature to implement by hand, but I think it should be available out of the box because it is so handy, and expected.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:6
  • Comments:16 (10 by maintainers)

github_iconTop GitHub Comments

2reactions
kamilmysliwieccommented, Oct 24, 2017

Hi @adammfrank, This pipe depends on the two 3rd party packages. That’s the reason why I don’t think it’s a good idea to make it a part of the core package, but I’m wondering about the new @nestjs/utils package. It might contain useful interceptors / guards as well as pipes (for example ParseXPipe / ValidationPipe) 🙂

1reaction
icepengcommented, Dec 30, 2017

ModelParserPipe is useful in this case:

import { IsInt, IsNumberString, IsPositive, Min } from 'class-validator';
import { Type } from 'class-transformer';

export class PhotoQuery {
  @Type(() => Number)
  @IsInt()
  @Min(0)
  readonly skip: number;

  @Type(() => Number)
  @IsInt()
  @IsPositive()
  readonly take: number;
}

Query is always parsed as string, so it is hard to validate with class-validator package. And you can validate and sanitize model with just one class definition.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to accept GET argument in Spring boot Controller and ...
1) @RestController is a combination of @Controller and @ResponseBody, which essentially means every method in your class will have a response ...
Read more >
Model Binding in ASP.NET Core | Microsoft Learn
Parameters of the Razor Pages handler method that a request is routed to. Public properties of a controller or PageModel class, if specified...
Read more >
Using Custom Data Binders in Spring MVC - Baeldung
This article will show how we can use Spring's Data Binding mechanism in order to make our code more clear and readable by...
Read more >
Using parameters in routes - Drupal Wiki
There is nothing more to provide in the route for the parameter conversion to happen because user is the name of an entity...
Read more >
7. Validation, Data Binding, and Type Conversion - Spring
Data binding is useful for allowing user input to be dynamically bound to the domain model of an application (or whatever objects you...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found