1 minute read

deno logo.png

Welcome ! Last time, we saw how to create a REST API in Deno using Danet. Today, we will add Body validation to it.

In order to do that simply add @Decorators from our validatte package to your classes !

Let’s look at the todo.controller.ts :

As we can see, we indicate that to create Todo, we need to do a POST request and send a Todo-ish object in the body. We get this object by using the @Body decorator.

However, the body format is not validated anywhere. Let’s say we decided that a description should not be less than 20 characters. With the current code, I would be able to send the following body:

{
  "title": 34,
  "content": "tooshort"
}

Notice that title is not a string and that content’s length is lower than 20 characters.

To enforce our body format, we simply need to slightly change our todo.class.ts as following :

By adding @IsString() and @LengthGreater(20), we are attaching validators.

Under the hood, the @Body decorator get the expected body type, and check if there is any validators attached to the class attributes. If there is, it calls validateObject() function from validatte against the body. If validateObject returns errors, an HTTP 400 BadRequest is thrown with explicit errors :

{
  "status": 400,
  "reasons":
  [
    {
      "property": "content",
      "errorMessage": "Length must be greater than 20",
      "constraints": [
        20
      ]
    }
  ]
}

Well, that’s it folks ! It wasn’t hard, now you know !

To learn more about Danet, check out our documentation : https://savory.github.io/Danet/

And the GitHub repository if you want to contribute : https://github.com/Savory/Danet

Updated: