Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/10017020 to your computer and use it in GitHub Desktop.
Save j5ik2o/10017020 to your computer and use it in GitHub Desktop.
protected def convertToEntity(json: J): E
protected def convertToEntityWithoutId(json: J): E
protected def createAction(implicit tjs: Writes[E], rds: Reads[J], ctx: EntityIOContext) = Action {
request =>
request.body.asJson.map {
json =>
json.validate[J].fold(defaultErrorHandler, {
validatedJson =>
repository.storeEntity(convertToEntityWithoutId(validatedJson)).map {
case (_, entity) =>
OkForCreatedEntity(entity.id)
}.recover {
case ex =>
BadRequestForIOError(ex)
}.get
})
}.getOrElse(InternalServerError)
}
protected def getAction(id: Long)(apply: Long => ID)
(implicit tjs: Writes[E], ctx: EntityIOContext) = Action {
val identifier = apply(id)
repository.resolveEntity(identifier).map {
entity =>
Ok(prettyPrint(toJson(entity)))
}.recoverWith {
case ex: EntityNotFoundException =>
Success(NotFoundForEntity(identifier))
}.getOrElse(InternalServerError)
}
protected def listAction(implicit tjs: Writes[E], ctx: EntityIOContext) = Action {
request =>
val offset = request.getQueryString("offset").map(_.toInt).getOrElse(0)
val limit = request.getQueryString("limit").map(_.toInt).getOrElse(100)
repository.resolveEntities(offset, limit).map {
entities =>
Ok(prettyPrint(JsArray(entities.map(toJson(_)))))
}.getOrElse(InternalServerError)
}
protected def updateAction(id: Long)(apply: Long => ID)
(implicit tjs: Writes[E], rds: Reads[J], ctx: EntityIOContext) = Action {
request =>
withTransaction {
implicit ctx =>
val identifier = apply(id)
repository.existByIdentifier(identifier).map {
exist =>
if (exist) {
request.body.asJson.map {
json =>
json.validate[J].fold(defaultErrorHandler, {
validatedJson =>
repository.storeEntity(convertToEntity(validatedJson)).map {
case (_, entity) =>
OkForCreatedEntity(entity.id)
}.recover {
case ex =>
BadRequestForIOError(ex)
}.get
})
}.getOrElse(InternalServerError)
} else {
NotFoundForEntity(identifier)
}
}.get
}
}
protected def deleteAction(id: Long)(apply: Long => ID)(implicit tjs: Writes[E], ctx: EntityIOContext) = Action {
val identifier = apply(id)
repository.deleteByIdentifier(identifier).map {
case (_, entity) =>
Ok(prettyPrint(toJson(entity)))
}.recoverWith {
case ex: EntityNotFoundException =>
Success(NotFoundForEntity(identifier))
}.getOrElse(InternalServerError)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment