Skip to content

Instantly share code, notes, and snippets.

@dozed
Forked from pollingj/Milestones
Last active December 17, 2015 15:29
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 dozed/5631680 to your computer and use it in GitHub Desktop.
Save dozed/5631680 to your computer and use it in GitHub Desktop.
import org.scalatra.ScalatraServlet
import org.scalatra.json.JacksonJsonSupport
import java.util.Date
import com.novus.salat.annotations._
import com.novus.salat.dao.SalatDAO
import com.novus.salat.global._
import com.novus.salat.grater
import com.mongodb.casbah.Imports._
import org.json4s.{CustomSerializer, Extraction, DefaultFormats}
import org.json4s.JsonAST.{JValue, JString}
import org.json4s.mongo.ObjectIdSerializer
case class Milestone(@Key("_id") id: Object = new ObjectId, name: String, date: Date)
object MilestoneDao extends SalatDAO[ Milestone , ObjectId](collection = MongoConnection()("my_db")("milestones"))
class MongoSample extends ScalatraServlet with JacksonJsonSupport {
// add support for ObjectId serialization
implicit val jsonFormats = DefaultFormats + new ObjectIdSerializer
before("/") {
contentType = formats("json")
}
get("/milestones") {
val id = new ObjectId
MilestoneDao.save(Milestone(id, "asd", new Date))
val m = MilestoneDao.findOneById(id).get
// 1. use json4s' Extraction + ObjectIdSerializer from json4s-mongo
val v: JValue = Extraction.decompose(m)
// 2. use salat's grater
// following https://github.com/novus/salat/wiki/JSON
val v2: JValue = grater[Milestone].toJSON(m)
// 3. set content type to application/json and return Milestone
// the render pipeline handles the conversion
contentType = formats("json")
m
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment