All Downloads are FREE. Search and download functionalities are using the official Maven repository.

play.api.rest.ResourceRouter.scala Maven / Gradle / Ivy

package play.api.rest

import scala.language.implicitConversions

import play.api.mvc.RequestHeader

/**
 * @author Karel Cemus
 */
trait ResourceRouter[Resource, Result] extends URLMatchers {

  private implicit def id2Res(id: Long): Res[Resource] = new Res(id, endpoint)

  var nested: Map[String, ResourceRouter[_, Res[Resource] => Result]] = Map.empty

  def attach(resource: String, router: ResourceRouter[_, Res[Resource] => Result]) = nested += resource -> router

  override protected def isResource(resource: String, request: RequestHeader): Boolean =
    nested.get(resource).exists(_.dispatcher.isDefinedAt(request))

  def prefix: String = ""

  def endpoint: ResourceHandler[Resource, Result]

  def dispatcher: PartialFunction[RequestHeader, Result] = {
    case LIST()       => endpoint.handleList
    case GET(id)      => endpoint.handleGet(id)
    case POST()       => endpoint.handlePost
    case PUT(id)      => endpoint.handlePut(id)
    case PATCH(id)    => endpoint.handlePatch(id)
    case HEAD(id)     => endpoint.handleHead(id)
    case DELETE(id)   => endpoint.handleDelete(id)
    case OPTIONS(id)  => endpoint.handleOptions(id)
    case NestedResource(id, resource, request) =>
      nested(resource).dispatcher(request)(id)
  }
}

class Router[T, R](_endpoint: ResourceHandler[T, R]) extends ResourceRouter[T, R] {
  override def endpoint: ResourceHandler[T, R] = _endpoint
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy