Created
May 3, 2023 04:11
-
-
Save csaltos/c6ce2ae355d82af5ee1afe95465f0323 to your computer and use it in GitHub Desktop.
MongoDB Scala converter using ReactiveMongo for reading and writing custom data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.myconverter | |
import reactivemongo.api.bson.BSONDocument | |
import reactivemongo.api.bson.BSONDocumentReader | |
import reactivemongo.api.bson.BSONDocumentWriter | |
import scala.util.Try | |
case class Address( | |
line1: String, | |
city: String, | |
postalCode: Option[String], | |
state: Option[String], | |
countryCode: String | |
) | |
object AddressConverter { | |
implicit object tkApiAddressBsonReader | |
extends BSONDocumentReader[Address] { | |
def readDocument(doc: BSONDocument): Try[Address] = | |
Try { | |
Address( | |
line1 = doc | |
.getAsOpt[String]("line1") | |
.getOrElse( | |
throw new IllegalStateException( | |
"address.line1 not found at database" | |
) | |
), | |
city = doc | |
.getAsOpt[String]("city") | |
.getOrElse( | |
throw new IllegalStateException( | |
"address.city not found at database" | |
) | |
), | |
postalCode = doc.getAsOpt[String]("postal_code"), | |
state = doc.getAsOpt[String]("state"), | |
countryCode = doc | |
.getAsOpt[String]("country_code") | |
.getOrElse( | |
throw new IllegalStateException( | |
"address.country_code not found at database" | |
) | |
) | |
) | |
} | |
} | |
implicit object TKApiAddressBsonWriter | |
extends BSONDocumentWriter[Address] { | |
def writeTry( | |
addressThriftVo: Address | |
): Try[BSONDocument] = | |
Try { | |
BSONDocument( | |
"line1" -> addressThriftVo.line1, | |
"city" -> addressThriftVo.city, | |
"postal_code" -> addressThriftVo.postalCode, | |
"state" -> addressThriftVo.state, | |
"country_code" -> addressThriftVo.countryCode | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment