Return all valid sections on bad request

This commit is contained in:
kageru 2020-07-04 22:56:36 +02:00
parent c8a66fbe73
commit 43f192178e
Signed by: kageru
GPG Key ID: 8282A2BEA4ADA3D2
3 changed files with 13 additions and 3 deletions

@ -10,12 +10,20 @@ public enum Section {
PASTA,
RICE,
MEAT,
FISH,
DAIRY,
HYGIENE;
HYGIENE,
BEVERAGES;
public static Either<String, Section> tryParse(String catName) {
return Stream.of(Section.values())
.find(c -> c.name().equalsIgnoreCase(catName))
.toEither("Category “%s” not found".formatted(catName));
}
public static String valuesAsString() {
return Stream.of(Section.values())
.map(Section::name)
.mkString("\nValid values are: ", ", ", "");
}
}

@ -4,6 +4,8 @@ import io.vavr.control.Either;
public record ShoppingItem(String name, Section section) {
public static Either<Resp, ShoppingItem> tryParse(String name, String category) {
return Section.tryParse(category).map(c -> new ShoppingItem(name, c));
return Section.tryParse(category)
.map(c -> new ShoppingItem(name, c))
.mapLeft(msg -> Resp.BAD_REQUEST.apply(msg + Section.valuesAsString()));
}
}

@ -10,7 +10,7 @@ import io.vavr.control.Either;
public record Store(String name, Seq<Section>sections) {
public static Either<Resp, Store> tryParse(String name, String sections) {
return Either.traverse(List.of(sections.split(",")), Section::tryParse)
.mapLeft(errors -> Resp.BAD_REQUEST.apply(errors.mkString("\n")))
.mapLeft(errors -> Resp.BAD_REQUEST.apply(errors.mkString("\n") + Section.valuesAsString()))
.map(secs -> new Store(name, secs));
}
}