Skip to main content

Converting Smithy4s Schemas and Services to Smithy

Using the smithy4s dynamic module you can convert a smithy4s service or schema into a smithy model. This guide will walk through the steps to do this.

Creating a DynamicSchemaIndex

The first step is to take the services and schemas you'd like included in your smithy model and add them to a DynamicSchemaIndex using the provided builder.

import smithy4s.dynamic.DynamicSchemaIndex

val dynamicSchemaIndex = DynamicSchemaIndex.builder
.addService[smithy4s.example.KVStoreGen]
.addSchema[smithy4s.example.FaceCard]
.build()
// dynamicSchemaIndex: DynamicSchemaIndex = smithy4s.dynamic.DynamicSchemaIndex$BuilderImpl$$anon$1@4e3331e2

Converting to Smithy Model

Now that we have a DynamicSchemaIndex, we can convert to a smithy model object from the smithy-model Java library. This feature is only supported on the JVM and not ScalaJS or Scala Native.

val model = dynamicSchemaIndex.toSmithyModel
// model: software.amazon.smithy.model.Model = software.amazon.smithy.model.Model@38521e1d

Rendering as a String

If you wish to render the smithy Model as a String, smithy-model provides a method to accomplish this.

import software.amazon.smithy.model.shapes.SmithyIdlModelSerializer
import scala.jdk.CollectionConverters._
import java.nio.file.Path

val smithyFiles: Map[Path, String] =
SmithyIdlModelSerializer
.builder()
.build()
.serialize(model)
.asScala
.toMap
// smithyFiles: Map[Path, String] = Map(
// smithy4s.example.smithy -> """$version: "2.0"
//
// namespace smithy4s.example
//
// service KVStore {
// operations: [
// Delete
// Get
// Put
// ]
// }
//
// operation Delete {
// input: Key
// output: Unit
// errors: [
// KeyNotFoundError
// UnauthorizedError
// ]
// }
//
// operation Get {
// input: Key
// output: Value
// errors: [
// KeyNotFoundError
// UnauthorizedError
// ]
// }
//
// operation Put {
// input: KeyValue
// output: Unit
// errors: [
// UnauthorizedError
// ]
// }
//
// structure Key {
// @required()
// key: String
// }
//
// @error("client")
// structure KeyNotFoundError {
// @required()
// message: String
// }
// ...