Scala read method annotations from another project

旧城冷巷雨未停 提交于 2021-01-29 16:14:53

问题


I have a sbt config with scala play! server, a scalajs client, and shared project which contains classes which are passed between the two.

I want my client to have strong type information for the server API calls so I'm writing a task that for each route in the routes file builds a corresponding method in the client. I have a prototype that is able to parse almost all of the information I need out of the routes file. The only thing I can't get is return types.

Here's what I have so far (I realize it doesn't handle everything but it works for all of the basic cases I'm working with right now):

case class RouteDef(
        method: String,
        url: String,
        pack: String,
        controller: String,
        fn: String,
        args: Option[Array[String]],
        retType: String = "Array[Byte]",
        retFormat: String = "application/json"
      ) {
        def interpolatedUrl: String = {
          ":(?<symbol>[^/]+)".r.replaceAllIn(url, (matc) => "\\${${symbol}}")
        }

        override def toString: String = {
          s"""  import play.api.libs.json.{Json,Reads}
  import org.scalajs.dom.ext.Ajax.InputData
  import scala.concurrent.Future
  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.util.Try
  import org.scalajs.dom.XMLHttpRequest
  import org.scalajs.dom.ext.Ajax

  def ${fn}(${args match {
    case Some(a) => a.mkString(", ") + ","
    case None => ""
  }} timeout: Int = 0, headers: Map[String, String] = Map.empty, withCredentials: Boolean = false) : Future[${retType}] = {
    Ajax(\"${method}\", \"${interpolatedUrl}\", null, timeout, headers, withCredentials, \"${retFormat}\").transform(
      (x: Try[XMLHttpRequest]) => Try(Json.parse(x.get.responseText).as[${retType}])
    )
  }
"""
        }
      }

I thought about adding an annotation to each of my method calls, but then I don't have a good way to parse them out. I tried using scalac -Xshow-class, but it doesn't show types or annotations.

I thought about trying to parse the class file manually, but it seems like I would run into a lot of corner cases that would make it a massive headache.

Is there any good way to translate to full path to a method definition to get the annotations of that method?

来源:https://stackoverflow.com/questions/61446926/scala-read-method-annotations-from-another-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!