Skip to content

Commit

Permalink
Add try / catch and fallback for getUrlInfo (#118)
Browse files Browse the repository at this point in the history
Add test

Signed-off-by: Logan Graham <[email protected]>

Signed-off-by: Logan Graham <[email protected]>
Co-authored-by: Logan Graham <[email protected]>
  • Loading branch information
omacranger and Logan Graham authored Oct 21, 2022
1 parent 04535af commit ffab24a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,29 @@ export const formatTime = (time) => {
};

export const getUrlInfo = (url) => {
const urlInfo = new URL(url);
const pathSplit = urlInfo.pathname.split('/');
const fileName = (
pathSplit[pathSplit.length - 1].trim() ?
pathSplit[pathSplit.length - 1] : pathSplit[pathSplit.length - 2]
) + urlInfo.search;
// If there's an invalid URL (resource identifier, etc) the constructor would throw an exception.
// Return a 'placeholder' object with default values in the event the passed value cannot be
// parsed.
try {
const urlInfo = new URL(url);
const pathSplit = urlInfo.pathname.split('/');
const fileName = (
pathSplit[pathSplit.length - 1].trim() ?
pathSplit[pathSplit.length - 1] : pathSplit[pathSplit.length - 2]
) + urlInfo.search;

return {
domain: urlInfo.host,
filename: fileName || urlInfo.href,
url: urlInfo.href,
};
return {
domain: urlInfo.host,
filename: fileName || urlInfo.href,
url: urlInfo.href,
};
} catch (er) {
return {
domain: 'N/A',
filename: url ?? 'N/A',
url,
};
}
};

export const parseSize = ({ bodySize, _transferSize, headers, content }) => {
Expand Down Expand Up @@ -311,7 +322,7 @@ export const calcChartAttributes = (data, maxTime, cx, index, cy = null) => {

Object.keys(TIMINGS).forEach((key) => {
const timingInfo = TIMINGS[key];
const dataKey = Array.isArray(timingInfo.dataKey) ? timingInfo.dataKey.find(key => data[key]) : timingInfo.dataKey
const dataKey = Array.isArray(timingInfo.dataKey) ? timingInfo.dataKey.find((key) => data[key]) : timingInfo.dataKey;
const value = data[dataKey];
if (value <= 0) {
return;
Expand Down
11 changes: 11 additions & 0 deletions tests/__tests__/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ describe('utils', () => {
expect(utils.getUrlInfo(url)).toMatchSnapshot();
});

it('getUrlInfo non standard url / resource identifier', () => {
const resourceName = 'ResourceIdentifierString';
const urlInfo = utils.getUrlInfo(resourceName);

expect(urlInfo).toEqual({
domain: 'N/A',
filename: resourceName,
url: resourceName,
});
});

it('parseSize', () => {
const { response } = networkDataMock.log.entries[0];
expect(utils.parseSize(response)).toMatchSnapshot();
Expand Down

0 comments on commit ffab24a

Please sign in to comment.