Skip to content

Commit

Permalink
fix: reference resolution issue with base URI change, fixes #1414
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Feb 1, 2021
1 parent 0b7567b commit c91e8ba
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/compile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export function resolveSchema(
): SchemaEnv | undefined {
const p = URI.parse(ref)
const refPath = _getFullPath(p)
const baseId = getFullPath(root.baseId)
let baseId = getFullPath(root.baseId)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
Expand All @@ -262,7 +262,11 @@ export function resolveSchema(

if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) return new SchemaEnv({schema: schOrRef.schema, root, baseId})
if (id === normalizeId(ref)) {
const {schema} = schOrRef
if (schema.$id) baseId = resolveUrl(baseId, schema.$id)
return new SchemaEnv({schema, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
}

Expand Down
35 changes: 35 additions & 0 deletions spec/issues/1414_base_uri_change.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import _Ajv from "../ajv"
import assert = require("assert")

const schema1 = {
$id: "one",
type: "object",
properties: {
foo: {$ref: "#/definitions/foo"},
},
definitions: {
foo: {$ref: "two"},
},
}

const schema2 = {
$id: "two",
type: "object",
properties: {
bar: {$ref: "#/definitions/bar"},
},
definitions: {
bar: {type: "string"},
},
}

describe("issue 1414: base URI change", () => {
it("should compile schema", () => {
const ajv = new _Ajv()
ajv.addSchema(schema2)
const validate = ajv.compile(schema1)
assert.strictEqual(typeof validate, "function")
assert.strictEqual(validate({foo: {bar: 1}}), false)
assert.strictEqual(validate({foo: {bar: "1"}}), true)
})
})

0 comments on commit c91e8ba

Please sign in to comment.