-
I believe this to be a very simple question, that somehow I can't quite see the answer to. Smithy must be generating Json encoders / decoders for it's case classes. Is it possible to access / use those decoders directly? I have a weird situation where I want to tamper with some JSON (directly (!)) before passing it on... but somehow I?m not seeing how to en/decode the smithy case classes manually... |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 9 replies
-
Hi @Quafadas, Smithy4s does indeed create encoders/decoders for the shapes you define in your specs. They're not generated as Scala sources but rather derived at runtime. You can access an instance of such a decoder/encoder, but you have to be aware of the following:
With all of that, here's what you could do to make instances of these encoders/decoders for //> using scala "2.13.8"
//> using lib "com.disneystreaming.smithy4s::smithy4s-http4s:0.14.2"
import smithy4s.schema.Schema
import smithy4s.http.PayloadError
import smithy4s.http4s.SimpleRestJsonBuilder
object codecs {
def makeDecoder[A: Schema]: String => Either[PayloadError, A] = {
val codecApi = SimpleRestJsonBuilder.codecs
val codec = codecApi.compileCodec(implicitly[Schema[A]])
s => codecApi.decodeFromByteArray(s.getBytes())
}
def makeEncoder[A: Schema]: A => String = {
val codecApi = SimpleRestJsonBuilder.codecs
val codec = codecApi.compileCodec(implicitly[Schema[A]])
codecApi.writeToArray(codec, _)
}
} Then you can define and use your codecs. object usage {
// generated code will look something like this
case class Foo(s: String)
object Foo {
// Every smithy4s-generated type has an implicit `Schema` available.
implicit val schema: Schema[Foo] = ???
}
// keep in mind to keep this out of the hot loop
val fooEncoder = codecs.makeEncoder[Foo]
def myBusinessLogic(foo: Foo): Unit = {
println(fooEncoder.apply(foo))
}
}
|
Beta Was this translation helpful? Give feedback.
-
@Quafadas can you elaborate on what you mean about "passing it on" ? |
Beta Was this translation helpful? Give feedback.
-
This would be the minimal subset. Both the nodes and edges are / will each become their own ADT later, but i haven't gotten around to that part (successfully) yet...
|
Beta Was this translation helpful? Give feedback.
Hi @Quafadas, Smithy4s does indeed create encoders/decoders for the shapes you define in your specs. They're not generated as Scala sources but rather derived at runtime.
You can access an instance of such a decoder/encoder, but you have to be aware of the following:
@simpleRestJson
it's not going to be difficult