Created
June 29, 2019 05:58
-
-
Save NomadBlacky/6d01d75ec917492f56f1d096343ce672 to your computer and use it in GitHub Desktop.
esa.io のAPIを叩いて執筆数ランキングを出力するScalaスクリプト #ScalaMatsuri
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import upickle.default._ | |
lazy val token = sys.env.getOrElse("ESA_TOKEN", throw new IllegalArgumentException("Not found the environment variable: ESA_TOKEN")) | |
case class PostsData(posts: Seq[Post], next_page: Int = 0) | |
case class Post(number: Int, name: String, wip: Boolean, created_by: Author) | |
case class Author(name: String) | |
implicit val postsDataR: Reader[PostsData] = macroR | |
implicit val postR: Reader[Post] = macroR | |
implicit val authorR: Reader[Author] = macroR | |
@main | |
def main(team: String, query: String = "", quiet: Boolean = false): Unit = { | |
val allPosts = getPosts(team, query, quiet) | |
val ranking = allPosts.groupBy(_.created_by.name).toSeq.sortBy(_._2.size).reverse | |
println("=== RANKING ===") | |
ranking.foreach { case (author, posts) => println(s"$author : ${posts.size} (wip: ${posts.count(_.wip)})") } | |
} | |
def getPosts(team: String, query: String, quiet: Boolean): Seq[Post] = { | |
def loop(acc: Seq[Post], page: Int = 1): Seq[Post] = { | |
val response = requests.get( | |
url = s"https://api.esa.io/v1/teams/$team/posts", | |
params = Seq("q" -> query, "page" -> page.toString, "par_page" -> "100"), | |
headers = Seq("Authorization" -> s"Bearer $token") | |
) | |
if (!quiet) println(response) | |
if (!response.is2xx) { | |
throw new IllegalStateException(s"Failed API call: $response") | |
} | |
val data = read[PostsData](response.text) | |
val posts = acc ++ data.posts | |
if (data.next_page == 0) posts else loop(posts, data.next_page) | |
} | |
loop(Seq.empty) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment