Skip to content

Codec derivation#

To perform any database operation which involves data fetching or updating, it is required to serialize and deserialize data to and from BSON. zio-mongo provides codecs for all the basic types and also provides a way to derive codecs for your own types. To encode and decode case classes and sealed traits, currently zio-mongo can be used with zio-json and circe

Deriving ZIO-JSON codecs#

Dependency

Maven Central

libraryDependencies +=  "com.bilal-fazlani.zio-mongo" %% "zio-json-codec" % zioMongoVersion

You can derive codes for case classes using derives keyword

import com.bilalfazlani.zioMongo.codecs.zioJson.{ given, * }
import zio.json.JsonCodec
import org.bson.types.ObjectId

case class Person(
    _id: ObjectId, 
    name: String, 
    lastName: String, 
    age: Int
  ) derives JsonCodec

Another way to derive codecs is manualling invoking a macro

import com.bilalfazlani.zioMongo.codecs.zioJson.{ given, * }
import zio.json.JsonCodec
import org.bson.types.ObjectId

case class Person(
    _id: ObjectId,
    name: String,
    lastName: String,
    age: Int
) {
  given JsonCodec[Person] = zio.json.DeriveJsonCodec.gen[Person]
}

Example

Deriving Circe codecs#

Dependency

Maven Central

libraryDependencies +=  "com.bilal-fazlani.zio-mongo" %% "circe-codec" % zioMongoVersion

You can derive circe codecs using derives keyword


or by manually invoking a macro

import org.bson.types.ObjectId
import com.bilalfazlani.zioMongo.codecs.circe.given
import io.circe.Codec.AsObject

case class Person(
    _id: ObjectId,
    name: String,
    lastName: String,
    age: Int
) derives AsObject

Alternatively, you can use semi-automatic derivation using io.circe.generic.semiauto._ import where codecs are needed

import org.bson.types.ObjectId
import com.bilalfazlani.zioMongo.codecs.circe.given
import io.circe.generic.semiauto._
import io.circe.Codec

case class Person(
    _id: ObjectId,
    name: String,
    lastName: String,
    age: Int
)

object Person {
  given Codec[Person] = deriveCodec[Person]
}

When using cirece, you can also use fully automatic derivation using io.circe.generic.auto._ import where codecs are needed

Example