@@ -9,6 +9,7 @@ const { randomUUID } = require('crypto')
9
9
10
10
const validate = require ( './schema-validator' )
11
11
const Serializer = require ( './serializer' )
12
+ const RefResolver = require ( './ref-resolver' )
12
13
const buildAjv = require ( './ajv' )
13
14
14
15
let largeArraySize = 2e4
@@ -58,19 +59,12 @@ function resolveRef (location, ref) {
58
59
const jsonPointer = ref . slice ( hashIndex ) || '#'
59
60
60
61
const schemaRef = schemaId + jsonPointer
62
+ const schema = refResolver . getSchema ( schemaRef )
61
63
62
- let ajvSchema
63
- try {
64
- ajvSchema = ajvInstance . getSchema ( schemaRef )
65
- } catch ( error ) {
64
+ if ( schema === undefined ) {
66
65
throw new Error ( `Cannot find reference "${ ref } "` )
67
66
}
68
67
69
- if ( ajvSchema === undefined ) {
70
- throw new Error ( `Cannot find reference "${ ref } "` )
71
- }
72
-
73
- const schema = ajvSchema . schema
74
68
if ( schema . $ref !== undefined ) {
75
69
return resolveRef ( { schema, schemaId, jsonPointer } , schema . $ref )
76
70
}
@@ -83,6 +77,7 @@ const objectReferenceSerializersMap = new Map()
83
77
84
78
let rootSchemaId = null
85
79
let ajvInstance = null
80
+ let refResolver = null
86
81
let contextFunctions = null
87
82
88
83
function build ( schema , options ) {
@@ -95,11 +90,13 @@ function build (schema, options) {
95
90
options = options || { }
96
91
97
92
ajvInstance = buildAjv ( options . ajv )
93
+ refResolver = new RefResolver ( )
98
94
rootSchemaId = schema . $id || randomUUID ( )
99
95
100
96
isValidSchema ( schema )
101
97
extendDateTimeType ( schema )
102
98
ajvInstance . addSchema ( schema , rootSchemaId )
99
+ refResolver . addSchema ( schema , rootSchemaId )
103
100
104
101
if ( options . schema ) {
105
102
const externalSchemas = clone ( options . schema )
@@ -114,8 +111,9 @@ function build (schema, options) {
114
111
schemaKey = key + externalSchema . $id // relative URI
115
112
}
116
113
117
- if ( ajvInstance . getSchema ( schemaKey ) === undefined ) {
114
+ if ( refResolver . getSchema ( schemaKey ) === undefined ) {
118
115
ajvInstance . addSchema ( externalSchema , schemaKey )
116
+ refResolver . addSchema ( externalSchema , key )
119
117
}
120
118
}
121
119
}
@@ -178,6 +176,7 @@ function build (schema, options) {
178
176
const stringifyFunc = contextFunc ( ajvInstance , serializer )
179
177
180
178
ajvInstance = null
179
+ refResolver = null
181
180
rootSchemaId = null
182
181
contextFunctions = null
183
182
arrayItemsReferenceSerializersMap . clear ( )
@@ -493,6 +492,7 @@ function mergeAllOfSchema (location, schema, mergedSchema) {
493
492
494
493
mergedSchema . $id = `merged_${ randomUUID ( ) } `
495
494
ajvInstance . addSchema ( mergedSchema )
495
+ refResolver . addSchema ( mergedSchema )
496
496
location . schemaId = mergedSchema . $id
497
497
location . jsonPointer = '#'
498
498
}
0 commit comments