Skip to content

Commit 794a8ce

Browse files
committed
fix: refactor code into shared method
1 parent de5e4ff commit 794a8ce

File tree

1 file changed

+14
-23
lines changed

1 file changed

+14
-23
lines changed

src/reference-resolver.ts

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -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 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;
@@ -178,12 +174,7 @@ export default (fetch: any, fs: any) => {
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

Comments
 (0)