Use an enum instead of a boolean to differentiate search

It's not very likely to have more modes of search besides normal and
trashed, but got surprised in that way quite often and it's nicer this
way anyways.
This commit is contained in:
eikek
2021-08-14 15:08:29 +02:00
parent a7b74bd5ae
commit edb344314f
7 changed files with 85 additions and 23 deletions

View File

@ -0,0 +1,43 @@
/*
* Copyright 2020 Docspell Contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package docspell.common
import cats.data.NonEmptyList
import io.circe.Decoder
import io.circe.Encoder
sealed trait SearchMode { self: Product =>
final def name: String =
productPrefix.toLowerCase
}
object SearchMode {
final case object Normal extends SearchMode
final case object Trashed extends SearchMode
def fromString(str: String): Either[String, SearchMode] =
str.toLowerCase match {
case "normal" => Right(Normal)
case "trashed" => Right(Trashed)
case _ => Left(s"Invalid search mode: $str")
}
val all: NonEmptyList[SearchMode] =
NonEmptyList.of(Normal, Trashed)
def unsafe(str: String): SearchMode =
fromString(str).fold(sys.error, identity)
implicit val jsonDecoder: Decoder[SearchMode] =
Decoder.decodeString.emap(fromString)
implicit val jsonEncoder: Encoder[SearchMode] =
Encoder.encodeString.contramap(_.name)
}