Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added defaults to reduce boilerplate of creating asyncapi #94

Merged
merged 2 commits into from
Jul 21, 2023

Conversation

soujiro32167
Copy link

@soujiro32167 soujiro32167 commented Jul 18, 2023

Use case: I have a bunch of avro codecs, and I want to generate docs for Backstage

import org.apache.avro.Schema
import sttp.apispec.ReferenceOr
import sttp.apispec.asyncapi.*

import scala.collection.immutable.ListMap
import scala.jdk.CollectionConverters.*

case class EventDescription(schema: Schema, topic: String, pubSub: PubSub)

sealed trait PubSub

object PubSub {
  case object Subscribe extends PubSub

  case object Publish extends PubSub
}

def schemaToMessage(schema: Schema): Message =
  if (schema.isUnion)
    OneOfMessage(schema.getTypes.asScala.map(s => Message.singleInline(s.toString, Some("application/vnd.apache.avro+yaml;version=1.9.0"))).toList)
  else
    Message.singleInline(schema.toString, Some("application/vnd.apache.avro+yaml;version=1.9.0"))

def avroChannelMessage(schema: Schema, pubSub: PubSub): ChannelItem =
  pubSub match {
    case PubSub.Publish =>
      ChannelItem.publish(Operation.inlineMessage(schemaToMessage(schema)))
    case PubSub.Subscribe =>
      ChannelItem.subscribe(Operation.inlineMessage(schemaToMessage(schema)))
  }

def mkChannels(events: List[EventDescription]): ListMap[String, ReferenceOr[ChannelItem]] =
  ListMap.from(
    events.map(e => e.topic -> Right(avroChannelMessage(e.schema, e.pubSub)))
  )

def makeAsyncApi(title: String, version: String, events: List[EventDescription]): AsyncAPI = {

  AsyncAPI(
    info = Info(
      title = title,
      version = version
    ),
    channels = mkChannels(events)
  )
}

@adamw adamw merged commit 31fa52e into softwaremill:master Jul 21, 2023
@adamw
Copy link
Member

adamw commented Jul 21, 2023

Thanks!

@soujiro32167 soujiro32167 deleted the less-boilerplate branch July 21, 2023 14:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants