- Also add path escaping

This commit is contained in:
Ferdi Koomen 2021-09-27 18:53:58 +02:00
parent f77b0b7558
commit 17d3c74afa
2 changed files with 13 additions and 9 deletions

View File

@ -1,6 +1,9 @@
import type { OpenApi } from '../interfaces/OpenApi';
import type { OpenApiReference } from '../interfaces/OpenApiReference';
const ESCAPED_REF_SLASH = /~1/g;
const ESCAPED_REF_TILDE = /~0/g;
export function getRef<T>(openApi: OpenApi, item: T & OpenApiReference): T {
if (item.$ref) {
// Fetch the paths to the definitions, this converts:
@ -13,9 +16,10 @@ export function getRef<T>(openApi: OpenApi, item: T & OpenApiReference): T {
// Try to find the reference by walking down the path,
// if we cannot find it, then we throw an error.
let result: any = openApi;
paths.forEach((path: string): void => {
if (result.hasOwnProperty(path)) {
result = result[path];
paths.forEach(path => {
const decodedPath = decodeURIComponent(path.replace(ESCAPED_REF_SLASH, '/').replace(ESCAPED_REF_TILDE, '~'));
if (result.hasOwnProperty(decodedPath)) {
result = result[decodedPath];
} else {
throw new Error(`Could not find reference: "${item.$ref}"`);
}

View File

@ -1,8 +1,8 @@
import type { OpenApi } from '../interfaces/OpenApi';
import type { OpenApiReference } from '../interfaces/OpenApiReference';
const escapedSlash = /~1/g;
const escapedTilde = /~0/g;
const ESCAPED_REF_SLASH = /~1/g;
const ESCAPED_REF_TILDE = /~0/g;
export function getRef<T>(openApi: OpenApi, item: T & OpenApiReference): T {
if (item.$ref) {
@ -16,10 +16,10 @@ export function getRef<T>(openApi: OpenApi, item: T & OpenApiReference): T {
// Try to find the reference by walking down the path,
// if we cannot find it, then we throw an error.
let result: any = openApi;
paths.forEach((path: string): void => {
path = decodeURIComponent(path.replace(escapedSlash, '/').replace(escapedTilde, '~'));
if (result.hasOwnProperty(path)) {
result = result[path];
paths.forEach(path => {
const decodedPath = decodeURIComponent(path.replace(ESCAPED_REF_SLASH, '/').replace(ESCAPED_REF_TILDE, '~'));
if (result.hasOwnProperty(decodedPath)) {
result = result[decodedPath];
} else {
throw new Error(`Could not find reference: "${item.$ref}"`);
}