2017-08-15 2 views
0

J'ai appris Scala, Slick, pendant 2 mois Akka et j'ai eu un problème lors de faire un projet de ... AkkaSlick Scala - colonne Omettre ID (auto_increment)

// This case class is to use for parsing data from request 
// case class UserTransaction(sender: String, recipient: String, amount: Int) 

//This one is to use for reflecting database 
case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int) 

class UserTransactionModelDB(tag: Tag) extends Table[UserTransactionDB](tag, "usertransaction") 
{ 
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc) 
    def sender = column[String]("sender") 
    def recipient = column[String]("recipient") 

    def amount = column[Int]("amount") 

    override def * = 

     (sender, recipient, amount, id) <> (UserTransactionDB.tupled, UserTransactionDB.unapply) 

} 

Je veux envoyer un POST demande (JSON) à Akka comme ceci:

{"sender" : "S" , "recipient" : "R", "amount" : 100} 

maintenant, je veux juste utiliser un seul cas de classe UserTransaction (sans champ « id » dans UserTransactionDB) non seulement pour tenir compte de la base de données et mais aussi pour analyser les données de demande. Est-ce possible ?

Merci et désolé pour mon anglais!

+0

Quelle bibliothèque JSON utilisez-vous? Je suppose que 'spray-json' ... dans ce cas, vous pourriez fournir un sérialiseur spray-json qui se débarrasse du champ' id'. – mfirry

+0

@mfirry Oui, j'utilise jsonFormat4 (UserTransactionDB.apply) – dOshu

+0

@mfirry Vouliez-vous dire celui-ci? https://github.com/spray/spray-json#providing-jsonformats-for-other-types – dOshu

Répondre

0

Essayez avec un format personnalisé ... quelque chose le long de ces lignes:

case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int) 

object MyJsonProtocol extends DefaultJsonProtocol { 
    implicit object UserTransactionJsonFormat extends RootJsonFormat[UserTransactionDB] { 
    def write(c: UserTransactionDB) = 
     JsArray(JsString(c.sender), JsString(c.recipient), JsNumber(c.amount)) 

    def read(value: JsValue) = value match { 
     case JsArray(Vector(JsString(sender), JsString(recipient), JsNumber(amount))) => 
     new UserTransactionDB(sender, recipient, amount.toInt) 
     case _ => deserializationError("UserTransactionDB expected") 
    } 
    } 
}