Giter Site home page Giter Site logo

circe-tagged-adt-codec-scala3's Introduction

Circe encoder/decoder Scala 3 implementation for ADT to JSON with a configurable type field.

Maven Central

This library provides an efficient, type safe and Scala 3 inline based ADT to JSON encoder/decoder for Circe, with configurable JSON type field mappings.

This is the rework of macro-based Scala 2 version here. This is not the same in terms of functionality, because meta-programming in Scala 3 is completely different.

For example this code doesn't support @annotations anymore, and using given instances as a replacement.

When you have ADTs defined like this

enum TestEvent {
  case Event1(anyYourField : String /*, ...*/)
  case Event2(anyOtherField : Long /*, ...*/)
}
// ...

and you would like to encode them to JSON like this:

{
  "type" : "my-event-1",
  "anyYourField" : "my-data", 
  "..." : "..."
}

The main objectives here are:

  • Avoid JSON type field in Scala case class definitions.
  • Configurable JSON type field values, and their mapping to case classes. They don't have to be Scala class names.
  • Avoid writing circe Encoder/Decoder manually.

Scala support

  • Scala v3
  • Scala.js v1.6+

Getting Started

Add the following to your build.sbt:

libraryDependencies += "org.latestbit" %% "circe-tagged-adt-codec" % "0.10.1"

or if you need Scala.js support:

libraryDependencies += "org.latestbit" %%% "circe-tagged-adt-codec" % "0.10.1"

Usage

import io.circe._
import io.circe.parser._
import io.circe.syntax._

// One import for this ADT/JSON codec
import org.latestbit.circe.adt.codec._

enum TestEvent derives JsonTaggedAdt.Encoder, JsonTaggedAdt.Decoder {
  case Event1(anyYourField : String /*, ...*/)
  case Event2(anyOtherField : Long /*, ...*/)
  case Event3 // No fields  
}

val testEvent : TestEvent = TestEvent.TestEvent1("test")
val testJsonString : String = testEvent.asJson.dropNullValues.noSpaces

// Decoding
decode[TestEvent] (testJsonString) match {
   case Right(model : TestEvent) => // ...
}

Tag configurations

Now we want to provide mapping between tag in JSON and case classes:

import io.circe._
import io.circe.parser._
import io.circe.syntax._

// One import for this ADT/JSON codec
import org.latestbit.circe.adt.codec._

// You still can use JsonTaggedAdt.Encoder/Decoder here, but `WithConfig` make
// configs explicitly required and without configuration it fails at compile time.
enum TestEvent derives JsonTaggedAdt.EncoderWithConfig, JsonTaggedAdt.DecoderWithConfig {
  case Event1(anyYourField : String /*, ...*/)
  case Event2(anyOtherField : Long /*, ...*/)
  case Event3 // No fields  
}

// Configuration
given JsonTaggedAdt.Config[TestEvent] = JsonTaggedAdt.Config.Values[TestEvent] (
  // Mappings between type/tag values and case classes/objects  
  mappings = Map(
    "ev1" -> JsonTaggedAdt.tagged[TestEvent.Event1],
    "ev2" -> JsonTaggedAdt.tagged[TestEvent.Event2],
    "ev3" -> JsonTaggedAdt.tagged[TestEvent.Event3.type]
  ),
  // Check if provided mappings aren't sufficient for all case classes (and throw exception if it is not)
  strict = true, // Default is false
  typeFieldName = "my-type" // Default is 'type'
)

// Encoding
val testEvent : TestEvent = TestEvent.Event1("test")
val testJsonString : String = testEvent.asJson.dropNullValues.noSpaces

// Decoding
decode[TestEvent] (testJsonString) match {
   case Right(model : TestEvent) => // ...
}

Pure enum constants / case objects ADT definitions support

Sometimes you just need tags constants themselves for declarations like this, without any additional type tags and objects to produce JSON strings for enum constants in json (instead of objects). To help with this scenario, ADT codec provides the specialized encoder and decoder implementations:

enum MyEnum derives JsonTaggedAdt.PureEncoder, JsonTaggedAdt.PureDecoder {
  case Enum1
  case Enum2
}

There are WithConfig versions of configs accordingly:

enum MyEnum derives JsonTaggedAdt.PureEncoderWithConfig, JsonTaggedAdt.PureDecoderWithConfig {
  case Enum1
  case Enum2
}

given JsonTaggedAdt.PureConfig[MyEnum] = JsonTaggedAdt.PureConfig.Values[MyEnum] (
  mappings = Map(
    "en1" -> JsonTaggedAdt.tagged[MyEnum.Event1.type],
    "en2" -> JsonTaggedAdt.tagged[MyEnum.Event2.type]
  )
)

Licence

Apache Software License (ASL)

Author

Abdulla Abdurakhmanov

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.