Skip to content

Instantly share code, notes, and snippets.

@rhinoman
Last active February 3, 2022 21:11
Show Gist options
  • Save rhinoman/5880814 to your computer and use it in GitHub Desktop.
Save rhinoman/5880814 to your computer and use it in GitHub Desktop.
Getting HAL style links for HATEOAS to map correctly to JSON in Scala. Assumes you're using json4s and Jackson. I'm using the below code with Scalatra -- my servlets have the 'JacksonJsonSupport' trait mixed in
//package object full o' utility functions for creating some HAL-style HATEOAS links
package object Hateoas{
//could add an additional field specifying MIME-type, for example
case class Link(href: String, method: String)
type HateoasLinks = Map[String, Link]
//case class for a response containing a Collection of items
case class ListResponse(_links: HateoasLinks, _embedded: Map[String, List[Any]])
object HateoasLinkFactory{
//could (should) add a function for generating a "custom" action link
def createSelfLink(uri: String) = {
("self" -> new Link(uri, "GET"))
}
//create Create!
def createCreateLink(uri: String) = {
("create" -> new Link(uri, "POST"))
}
def createUpdateLink(uri: String) = {
("update" -> new Link(uri, "PUT"))
}
def createDeleteLink(uri: String) = {
("delete" -> new Link(uri, "DELETE"))
}
}
}
//feed the output of this function into your Json serializer
def addLinks(myData: MyData, accessLevel: String, serviceUri: String) = {
val elementUri: String = serviceUri + "/" + myData.id.toString
//Assume MyData has a field called _links of type HateoasLinks initialized to an empty Map
//Always add a self link
myData._links += HateoasLinkFactory.createSelfLink(elementUri)
accessLevel match {
case "admin" =>
//so let's say only an admin has access to Update or Delete a 'MyData' resource
myData._links += HateoasLinkFactory.createUpdateLink(elementUri)
myData._links += HateoasLinkFactory.createDeleteLink(elementUri)
}
myData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment