No orders for the Moon

Exercise 4 of 4 in chapter 2 · 100 XP · 3 objectives checked by tests

Topics covered: Validation422Error handling

Bastien wanted to test the app: he ordered a delivery to “the Moon” (la-lune), with no customer name. It went into the round, and Yanis spent a good hour looking for the Moon.

Your mission

  1. At the start of Store, validate the request: client is required and is at least 2 characters long; quartier is required and must be croix-rousse, presqu-ile, guillotiere or confluence.
  2. An invalid order responds 422 with {"erreurs": …}, the errors grouped by field, and does not join the round.
  3. A valid order goes through as before.

Reminder

ctx.Request().Validate(rules) uses Laravel's syntax: required, in:a,b,c, email… As in Laravel, min:2 counts a string's characters and compares a number's value (Goravel still accepts min_len, the rule's old, deprecated name). Validate returns two values: the validator and an error. That's Go's way of reporting a problem, without exceptions: you check err right after the call, with if err != nil. Here, err doesn't mean the order is invalid, but that the validation could not run (a badly written rule, for example).

The verdict is in the validator: validator.Fails(), then validator.Errors().All(), the messages by field and by rule. Unlike Laravel, Goravel doesn't respond on its own: sending back the 422 is up to you.