--- a/src/Pure/General/json_api.scala Tue Dec 21 19:42:20 2021 +0100
+++ b/src/Pure/General/json_api.scala Tue Dec 21 21:07:26 2021 +0100
@@ -6,6 +6,8 @@
package isabelle
+import java.net.URL
+
object JSON_API
{
@@ -14,11 +16,25 @@
def api_error(msg: String): Nothing = error("JSON API error: " + msg)
def api_errors(msgs: List[String]): Nothing = error(("JSON API errors:" :: msgs).mkString("\n "))
+ class Service(val url: URL)
+ {
+ override def toString: String = url.toString
+
+ def get(route: String): HTTP.Content =
+ HTTP.Client.get(if (route.isEmpty) url else new URL(url, route))
+
+ def get_root(route: String = ""): Root =
+ Root(get(if (route.isEmpty) "" else "/" + route).json)
+ }
+
sealed case class Root(json: JSON.T)
{
def get_links: Option[Links] = JSON.value(json, "links").map(Links)
+ def get_next: Option[Service] = get_links.flatMap(_.get_next)
+
def get_included: List[Resource] = JSON.list(json, "included", Resource.some).getOrElse(Nil)
def get_data: Option[Data] = JSON.value(json, "data").map(Data(_, get_included))
+
def get_errors: Option[List[JSON.T]] = JSON.list(json, "errors", Some(_))
def ok: Boolean = get_errors.isEmpty
@@ -29,14 +45,19 @@
case Some(errs) => api_errors(errs.map(JSON.Format.apply))
}
def check_data: Data = check.get_data getOrElse api_error("missing data")
+ def check_resource: Resource = check_data.resource
+ def check_resources: List[Resource] = check_data.resources
override def toString: String = "Root(" + (if (ok) "ok" else "errors") + ")"
}
sealed case class Links(json: JSON.T)
{
- def get_next: Option[Root] =
- for (next <- JSON.value(json, "next") if next != null) yield Root(next)
+ def get_next: Option[Service] =
+ for {
+ JSON.Value.String(next) <- JSON.value(json, "next")
+ if Url.is_wellformed(next)
+ } yield new Service(Url(next))
override def toString: String =
if (get_next.isEmpty) "Links()" else "Links(next)"
--- a/src/Pure/Tools/flarum.scala Tue Dec 21 19:42:20 2021 +0100
+++ b/src/Pure/Tools/flarum.scala Tue Dec 21 21:07:26 2021 +0100
@@ -17,16 +17,14 @@
def server(url: URL): Server = new Server(url)
- class Server private[Flarum](url: URL)
+ class Server private[Flarum](url: URL) extends JSON_API.Service(url)
{
- override def toString: String = url.toString
+ def get_api(route: String): JSON_API.Root =
+ get_root("api" + (if (route.isEmpty) "" else "/" + route))
- def get(route: String): HTTP.Content =
- HTTP.Client.get(if (route.isEmpty) url else new URL(url, route))
-
- def get_api(route: String = ""): JSON_API.Root =
- JSON_API.Root(get("api" + (if (route.isEmpty) "" else "/" + route)).json)
-
- val root: JSON_API.Root = get_api()
+ val root: JSON_API.Root = get_api("")
+ def users: JSON_API.Root = get_api("users")
+ def groups: JSON_API.Root = get_api("groups")
+ def discussions: JSON_API.Root = get_api("discussions")
}
}