Skip to content
This repository has been archived by the owner on Jul 2, 2019. It is now read-only.

Commit

Permalink
Merge pull request #109 from apiaryio/kylef/escape-uri-template
Browse files Browse the repository at this point in the history
Escape generated URI Template variables
  • Loading branch information
pksunkara authored Jun 16, 2017
2 parents 1581e1f + af0d2d4 commit 2fd6365
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
- Parameters which define both an example (`x-example`) and `items` schema will
now use the `x-example` value as the example.

- URI Template variables are now correctly escaped.

# 0.12.0-beta.2

## Bug Fixes
Expand Down
17 changes: 10 additions & 7 deletions src/uri-template.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
import _ from 'lodash';

function escapeUriTemplateVariable(variable) {
return encodeURIComponent(variable)
.replace(/[-.!~*'()]/g, c => `%${c.charCodeAt(0).toString(16)}`);
}

export default function buildUriTemplate(basePath, href, pathObjectParams = [], queryParams = []) {
const parameterNames = _.chain(pathObjectParams)
.concat(queryParams)
.filter(parameter => parameter.in === 'query')
.uniqBy(parameter => parameter.name)
.map((parameter) => {
const name = escapeUriTemplateVariable(parameter.name);

if (parameter.collectionFormat === 'multi') {
return `${parameter.name}*`;
return `${name}*`;
}

return parameter.name;
return name;
})
.value();

if (parameterNames.length > 0) {
const queryString = parameterNames.join(',');
const full = `${basePath}${href}{?${queryString}}`;

// Before returning, we replace instances of `-` with `%2d`, but only when
// they occur inside of a template variable.
return full.replace(/\{.*?\}/g, match => match.replace('-', '%2d'));
return `${basePath}${href}{?${queryString}}`;
}

return basePath + href;
Expand Down
8 changes: 4 additions & 4 deletions test/uri-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,22 +94,22 @@ describe('URI Template Handler', () => {
});
});

context('when there are parameters with dashes', () => {
context('when there are parameters with reserved characters', () => {
const basePath = '/my-api';
const href = '/pet/{unique-id}';
const href = '/pet/{unique%2did}';
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tag-names',
name: 'tag-names[]',
required: true,
type: 'string',
},
];

it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, [], queryParams);
expect(hrefForResource).to.equal('/my-api/pet/{unique%2did}{?tag%2dnames}');
expect(hrefForResource).to.equal('/my-api/pet/{unique%2did}{?tag%2dnames%5B%5D}');
});
});

Expand Down

0 comments on commit 2fd6365

Please sign in to comment.