thecodexhub / books-directory

Books Directory app made with Dart Frog.
https://medium.com/@thecodexhubofficial/dart-frog-fast-minimalistic-backend-framework-for-dart-fcfca966c976
MIT License
7 stars 1 forks source link

Validate request body before route handler operation #1

Open thecodexhub opened 5 months ago

thecodexhub commented 5 months ago

Description

In the current scenario, for the POST request on /books, if there is a missing required field, it throws an error.

POST http://localhost:8080/books
Content-Type: application/json

{
  "description": "Timeless lessons on wealth, greed, and happiness doing well with money",
  "author": "Morgan Housel"
}

This request doesn't contain the name required field, so it cannot create a [Book] object in the following code, causing the route handler to fail.

final book = Book.fromJson(
  await context.request.json() as Map<String, dynamic>,
);

Solution

Check if the field is available in the request body, and if the value is of type [String]. The solution might become cumbersome for multiple fields and complex validation logic.

final reqBodyJson = await context.request.json() as Map<String, dynamic>;
if (!reqBodyJson.containsKey('name') && reqBodyJson['name'] is! String) {
  return Response.json(
    statusCode: HttpStatus.badRequest,
    body: 'The `name` field is missing in the request body',
  );
}
thecodexhub commented 5 months ago

The library is in progress! 🥳

https://pub.dev/packages/request_validator