Skip to content

Instantly share code, notes, and snippets.

@denen99
Created July 5, 2013 02:07
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 denen99/5931231 to your computer and use it in GitHub Desktop.
Save denen99/5931231 to your computer and use it in GitHub Desktop.
controller
---------------
package com.example.app
import org.scalatra._
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._
import com.example.app.models.User
import com.example.app.serializers.UserSerializer
class UsersController extends ScalatraServlet with JacksonJsonSupport {
implicit val jsonFormats = DefaultFormats + new UserSerializer
before() {
contentType = formats("json")
}
get("/:id") {
val userid = params.getOrElse("id", halt(400)).toInt
User.find(userid)
}
}
serializer
------------
package com.example.app.serializers
import com.example.app.models.User
import org.json4s.CustomSerializer
import org.json4s._
class UserSerializer extends CustomSerializer[User](format => ({
case JObject(
("id", JInt(id)) ::
("email", JString(email)) ::
("firstName" , JString(firstName)) ::
("lastName", JString(lastName)) :: Nil) =>
new User(1,email)
}, {
case user: User =>
JObject.apply(
"email" -> JString(user.email),
"id" -> JInt(user.id),
"status" -> JInt(200)
)
}))
model
--------------
package com.example.app.models
import scala.slick.driver.MySQLDriver.simple._
import Database.threadLocalSession
import com.example.app.SlickInit._
// DB Table
object Users extends Table[(Int,String)]("users") {
def id = column[Int]("id")
def email = column[String]("email")
def * = id ~ email
}
case class User(id:Int, email: String)
object User {
def find(id: Int) =
dbMaster withSession {
val q = for {
u <- Users if u.id === id
} yield u
q.first
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment