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

Add $ref resolution helper #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions argus/src/main/scala/argus/schema/SchemaHelpers.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package io.circe.argus.schema

import io.circe.{ACursor, Json, JsonNumber, JsonObject}
import io.circe.parser.parse
import cats.instances.all._
import cats.syntax.all._
import scala.io.Source

object SchemaHelpers {
def resolveRefs(schema: Json, subschemas: Map[String, Json]): ResolutionResult =
schema.foldWith(Resolver(schema, subschemas))

def resolveRefsFromResources(dir: String, main: String): ResolutionResult = {
val parts = dir.split("/")
val files = getFilenamesRec(parts.init.mkString("/"), parts.last)

val schemas = files.flatMap { path =>
val contents = Source.fromInputStream(getClass.getResourceAsStream(path)).mkString
parse(contents).map((path.drop(dir.length + 1), _)).toOption
}.toMap

resolveRefs(schemas(main), schemas)
}


def getFilenamesRec(base: String, path: String): List[String] = {
val resource = getClass.getResource(base + "/" + path)
val file = new java.io.File(resource.getPath)

if (file.exists) {
if (file.isDirectory) {
file.listFiles.toList.flatMap(f => getFilenamesRec(base + "/" + file.getName, f.getName))
} else {
List(base + "/" + file.getName)
}
} else {
Nil
}
}

case class ResolutionError(msg: String) extends RuntimeException(msg)

type ResolutionResult = Either[ResolutionError, Json]

case class Resolver(self: Json, subschemas: Map[String, Json])
extends Json.Folder[ResolutionResult] {
def onNull: ResolutionResult = Right(Json.Null)
def onNumber(value: JsonNumber): ResolutionResult = Right(Json.fromJsonNumber(value))
def onBoolean(value: Boolean): ResolutionResult = Right(Json.fromBoolean(value))
def onString(value: String): ResolutionResult = Right(Json.fromString(value))
def onArray(value: Vector[Json]): ResolutionResult = value.traverse(_.foldWith(this)).map(Json.fromValues(_))
def onObject(value: JsonObject): ResolutionResult = value.toVector.traverse {
case ("$ref", value) => resolve(value)
case (other, value) => value.foldWith(this).map(json => Vector((other, json)))
}.map(nested => Json.fromFields(nested.flatten))

private def failType() = ResolutionError("$ref field value must be a string")
private def failInvalidRef(ref: String) = ResolutionError("Invalid $ref: " + ref)
private def failUnknownResource(resource: String) = ResolutionError("Unknown resource: " + resource)
private def failInvalidPath(path: String) = ResolutionError("Invalid path: " + path)

private def extract(schema: Json, path: String): Either[ResolutionError, Vector[(String, Json)]] =
path.split("/").tail.foldLeft(schema.hcursor: ACursor)(_.downField(_))
.focus.toRight(failInvalidPath(path)).flatMap { resolved =>
resolved.asObject.toRight(failInvalidPath(path)).map(_.toVector)
}

private def resolve(value: Json): Either[ResolutionError, Vector[(String, Json)]] =
value.asString.toRight(failType()).flatMap { ref =>
ref.split("#") match {
case Array("", path) => extract(self, path)
case Array(subschema, path) =>
subschemas.get(subschema).toRight(failUnknownResource(subschema)).flatMap { schema =>
schema.foldWith(Resolver(schema, this.subschemas)).flatMap { processed =>
extract(processed, path)
}
}
case _ => Left(failInvalidRef(ref))
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"definitions": {
"Identifier": {
"type": "string",
"maxLength": 10
}
}
}
9 changes: 9 additions & 0 deletions argus/src/test/resources/relative-uri/schema/main.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"type": "object",
"description": "Example from Everit's tests",
"properties": {
"rect": {
"$ref": "props.json#/definitions/Rectangle"
}
}
}
21 changes: 21 additions & 0 deletions argus/src/test/resources/relative-uri/schema/props.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"definitions": {
"Rectangle": {
"type": "object",
"properties": {
"a": {
"$ref": "#/definitions/Size"
},
"b": {
"$ref": "#/definitions/Size"
},
"id": {
"$ref": "directory/subschemas.json#/definitions/Identifier"
}
}
},
"Size": {
"type": "number"
}
}
}
38 changes: 38 additions & 0 deletions argus/src/test/scala/argus/schema/SchemaHelpersSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package io.circe.argus.schema

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class SchemaHelpersSpec extends AnyFlatSpec with Matchers {
"SchemaHelper" should "resolve $refs in Json schemas" in {
val res = SchemaHelpers.resolveRefsFromResources("/relative-uri/schema", "main.json")

val expectedJson = """
{
"type" : "object",
"description" : "Example from Everit's tests",
"properties" : {
"rect" : {
"type" : "object",
"properties" : {
"a" : {
"type" : "number"
},
"b" : {
"type" : "number"
},
"id" : {
"type" : "string",
"maxLength" : 10
}
}
}
}
}
"""

val Right(expected) = io.circe.parser.parse(expectedJson)

res should ===(Right(expected))
}
}