@@ -121,19 +121,23 @@ export default (fetch: any, fs: any) => {
121121 return new Promise ( ( resolve ) => fs . readFile ( f , "utf8" , ( err : any , data : any ) => resolve ( data ) ) ) ;
122122 } ;
123123
124+ const resolvePointer = ( ref : string , root : any ) : any => {
125+ try {
126+ const withoutHash = ref . replace ( "#" , "" ) ;
127+ const pointer = Ptr . parse ( withoutHash ) ;
128+ return pointer . eval ( root ) ;
129+ } catch ( e ) {
130+ throw new InvalidJsonPointerRefError ( { $ref : ref } ) ;
131+ }
132+ } ;
133+
124134 /**
125135 * Given a $ref string, it will return the underlying pointed-to value.
126136 * For remote references, the root object is not used.
127137 */
128138 const resolveReference = async ( ref : string , root : any ) : Promise < any > => {
129139 if ( ref [ 0 ] === "#" ) {
130- const withoutHash = ref . replace ( "#" , "" ) ;
131- try {
132- const pointer = Ptr . parse ( withoutHash ) ;
133- return Promise . resolve ( pointer . eval ( root ) ) ;
134- } catch ( e ) {
135- throw new InvalidJsonPointerRefError ( { $ref : ref } ) ;
136- }
140+ return Promise . resolve ( resolvePointer ( ref , root ) ) ;
137141 }
138142
139143 const hashFragmentSplit = ref . split ( "#" ) ;
@@ -142,10 +146,7 @@ export default (fetch: any, fs: any) => {
142146 hashFragment = hashFragmentSplit [ hashFragmentSplit . length - 1 ] ;
143147 }
144148
145- let hashlessRef = ref ;
146- if ( hashFragment ) {
147- hashlessRef = ref . replace ( `#${ hashFragment } ` , "" ) ;
148- }
149+ const hashlessRef = hashFragmentSplit [ 0 ] ;
149150
150151 if ( await fileExistsAndReadable ( hashlessRef ) === true ) {
151152 const fileContents = await readFile ( hashlessRef ) ;
@@ -157,12 +158,7 @@ export default (fetch: any, fs: any) => {
157158 }
158159
159160 if ( hashFragment ) {
160- try {
161- const pointer = Ptr . parse ( hashFragment ) ;
162- return Promise . resolve ( pointer . eval ( reffedSchema ) ) ;
163- } catch ( e ) {
164- throw new InvalidJsonPointerRefError ( { $ref : ref } ) ;
165- }
161+ reffedSchema = resolvePointer ( hashFragment , reffedSchema ) ;
166162 }
167163
168164 return reffedSchema ;
@@ -172,18 +168,13 @@ export default (fetch: any, fs: any) => {
172168
173169 let result ;
174170 try {
175- result = await fetch ( ref ) . then ( ( r : any ) => r . json ( ) ) ;
171+ result = await fetch ( hashlessRef ) . then ( ( r : any ) => r . json ( ) ) ;
176172 } catch ( e ) {
177173 throw new InvalidRemoteURLError ( ref ) ;
178174 }
179175
180176 if ( hashFragment ) {
181- try {
182- const pointer = Ptr . parse ( hashFragment ) ;
183- return Promise . resolve ( pointer . eval ( result ) ) ;
184- } catch ( e ) {
185- throw new InvalidJsonPointerRefError ( { $ref : ref } ) ;
186- }
177+ result = resolvePointer ( hashFragment , result ) ;
187178 }
188179
189180 return result ;
0 commit comments