Skip to content

Commit

Permalink
fix: improved error handling on Oas.findOperation() calls (#628)
Browse files Browse the repository at this point in the history
  • Loading branch information
erunion authored Mar 29, 2022
1 parent 590cb9b commit 22198dd
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
50 changes: 50 additions & 0 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,56 @@ describe('#findOperation()', () => {
method: 'GET',
});
});

it('should not error if one of the paths in the API definition has a malformed path parameter', () => {
const oas = new Oas({
openapi: '3.0.1',
info: {
title: 'Some Test API',
version: '1',
},
paths: {
'/v1/endpoint': {
get: {
responses: {
200: {
description: 'OK',
},
},
},
},
'/}/v1/endpoint': {
get: {
summary:
"The path on this operation is malformed and will throw an error in `path-to-regexp` if we don't handle it.",
responses: {
200: {
description: 'OK',
},
},
},
},
},
});

const uri = 'https://example.com/v1/endpoint';
const method = 'get';

// Calling `findOperation` twice in this test so we can make sure that not only does it not
// throw an exception but that it still returns the data we want.
expect(() => {
oas.findOperation(uri, method);
}).not.toThrow(new TypeError('Unexpected CLOSE at 1, expected END'));

const res = oas.findOperation(uri, method);
expect(res.url).toStrictEqual({
origin: 'https://example.com',
path: '/v1/endpoint',
nonNormalizedPath: '/v1/endpoint',
slugs: {},
method: 'GET',
});
});
});
});

Expand Down
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,17 @@ function generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin:
return Object.keys(paths)
.map(path => {
const cleanedPath = normalizePath(path);
const matchStatement = match(cleanedPath, { decode: decodeURIComponent });
const matchResult = matchStatement(prunedPathName);

let matchResult: MatchResult;
try {
const matchStatement = match(cleanedPath, { decode: decodeURIComponent });
matchResult = matchStatement(prunedPathName) as MatchResult;
} catch (err) {
// If path matching fails for whatever reason (maybe they have a malformed path parameter)
// then we shouldn't also fail.
return;
}

const slugs: Record<string, string> = {};

if (matchResult && Object.keys(matchResult.params).length) {
Expand All @@ -157,6 +166,7 @@ function generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin:
});
}

// eslint-disable-next-line consistent-return
return {
url: {
origin,
Expand All @@ -168,6 +178,7 @@ function generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin:
match: matchResult,
};
})
.filter(Boolean)
.filter(p => p.match) as PathMatches;
}

Expand Down

0 comments on commit 22198dd

Please sign in to comment.