Alexis Hernandez
7 years ago
3 changed files with 62 additions and 0 deletions
@ -0,0 +1,22 @@ |
|||
package com.xsn.explorer.errors |
|||
|
|||
import com.alexitc.playsonify.models.{FieldValidationError, InputValidationError, PublicError} |
|||
import play.api.i18n.{Lang, MessagesApi} |
|||
|
|||
sealed trait PaginatedQueryError |
|||
|
|||
case object PaginatedQueryOffsetError extends PaginatedQueryError with InputValidationError { |
|||
override def toPublicErrorList(messagesApi: MessagesApi)(implicit lang: Lang): List[PublicError] = { |
|||
val message = messagesApi("error.paginatedQuery.offset") |
|||
val error = FieldValidationError("offset", message) |
|||
List(error) |
|||
} |
|||
} |
|||
|
|||
case class PaginatedQueryLimitError(maxValue: Int) extends PaginatedQueryError with InputValidationError { |
|||
override def toPublicErrorList(messagesApi: MessagesApi)(implicit lang: Lang): List[PublicError] = { |
|||
val message = messagesApi("error.paginatedQuery.limit", maxValue) |
|||
val error = FieldValidationError("limit", message) |
|||
List(error) |
|||
} |
|||
} |
@ -0,0 +1,37 @@ |
|||
package com.xsn.explorer.services.validators |
|||
|
|||
import com.alexitc.playsonify.core.ApplicationResult |
|||
import com.xsn.explorer.errors.{PaginatedQueryLimitError, PaginatedQueryOffsetError} |
|||
import com.xsn.explorer.models.base.{Limit, Offset, PaginatedQuery} |
|||
import org.scalactic.{Accumulation, Bad, Good} |
|||
|
|||
class PaginatedQueryValidator { |
|||
|
|||
private val MinOffset = 0 |
|||
private val LimitRange = 1 to 100 |
|||
|
|||
def validate(query: PaginatedQuery): ApplicationResult[PaginatedQuery] = { |
|||
Accumulation.withGood( |
|||
validateOffset(query.offset), |
|||
validateLimit(query.limit)) { |
|||
|
|||
PaginatedQuery.apply |
|||
} |
|||
} |
|||
|
|||
private def validateOffset(offset: Offset): ApplicationResult[Offset] = { |
|||
if (offset.int >= MinOffset) { |
|||
Good(offset) |
|||
} else { |
|||
Bad(PaginatedQueryOffsetError).accumulating |
|||
} |
|||
} |
|||
|
|||
private def validateLimit(limit: Limit): ApplicationResult[Limit] = { |
|||
if (LimitRange contains limit.int) { |
|||
Good(limit) |
|||
} else { |
|||
Bad(PaginatedQueryLimitError(LimitRange.last)).accumulating |
|||
} |
|||
} |
|||
} |
Loading…
Reference in new issue