djfdyuruiry / ts-lambda-api

Build REST API's using Typescript & AWS Lambda
MIT License
54 stars 15 forks source link

Add @bodyTyped decorator for automatic type coercion and validation #50

Closed revbingo closed 2 years ago

revbingo commented 3 years ago

A common gotcha of the current implementation of the @body decorator is that the method signature may define a type, but at runtime the actual object passed may really be of any type, or have other properties as well as those defined by the type. Even if it matches the properties, it is not an actual instance of the class.

This pull request adds the @bodyTyped decorator, for automatic coercion to a class using class-transformer, as well as optionally performing validation using class-validator. This allows a user to simply add the decorator and receive a runtime type-safe object that has already been validated and had any unwanted properties removed.

The signature is @bodyType(TypeConstructor, options?). Options are as per class-validator, with the addition of a validate option that enables the validation (by default the annotation creates the class but does not perform validation). A validation failure will return an HTTP 400 Bad Request with the relevant validation error messages.

Caveats: the type must be a class, not an interface, and it must have a default no-args constructor.

revbingo commented 3 years ago

hi Matt, sorry for the delay on my side too, things have been a bit busy - I will review shortly and make changes, thanks!

djfdyuruiry commented 2 years ago

Closing due to inactivity