首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spotify API接口

Spotify API接口
EN

Code Review用户
提问于 2013-12-14 21:21:41
回答 1查看 204关注 0票数 2

我正在尝试为spotify API创建一个scala接口。我用它来学习Scala。我的背景大多是蟒蛇。

代码语言:javascript
复制
import dispatch._, Defaults._

trait Request {
  val name: String
  val endpoint: String
}

case class Track(name: String) extends Request {
  override val endpoint = "track.json"
}

case class Album(name: String) extends Request {
  override val endpoint = "album.json"
}

case class Artist(name: String) extends Request {
  override val endpoint = "artist.json"
}

object Spotify {

  def getResponse(req: Request) = {
    val params = Map("q" -> req.name)
    val spotifyUrl = host("ws.spotify.com")

    spotifyUrl / "search"/ "1" / req.endpoint <<? params

  }

  val foo = Album("foo")
  val songs = Http(getResponse(foo) OK as.String)

}

我觉得getResponse应该是请求特性,或者什么的,因为它足够通用,只需要被覆盖的endpoint --但不确定。任何关于这类事情的结构的一般性建议都是有帮助的。

EN

回答 1

Code Review用户

回答已采纳

发布于 2013-12-14 21:58:14

把所有的东西都拆了。

我确信Scala老兵会比我说的更多,并且可能会对我的评论发表评论。

下面是对您的代码的一些更改和相应的注释。

代码语言:javascript
复制
import dispatch._, Defaults._

// decouple from any "master" class.
case class Track(name: String)

case class Album(name: String)

case class Artist(name: String)

// This is called a structural type. We are using a def
// because a val restricts extensibility.
type Named = {def name: String}

// Separate out the endpoints into their own category
object endpointResolver {

  // Use a partial function which you can re-use in order parts
  // of your program. You may use this in your testing as well.
  val endPoints: PartialFunction[Named, String] = {
    case _: Track => "track.json"
    case _: Album => "album.json"
    case _: Artist => "artist.json"
  }

  // use an implicit class. This allows you to add methods
  // to existing classes seamlessly.
  implicit class nrEndpoint(namedRequest: Named) {
    def endpoint: String =
      endPoints apply namedRequest
  }

}

object Spotify {

  // Specify the return type. I was not sure what it was initially.
  def getResponse(req: Named): Req = {

    val params = Map("q" -> req.name)

    val spotifyUrl = host("ws.spotify.com")

    // import and utilise this implicit class
    import endpointResolver.nrEndpoint

    spotifyUrl / "search"/ "1" / req.endpoint <<? params

  }

  val foo = Album("foo")

  // OK is another example of an implicit being used. Use an IDE
  // such as IntelliJ IDEA to navigate through the vast depths
  // of Scala source.
  val songs = Http(getResponse(foo) OK as.String)

}
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/37375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档