Skip to content

Commit

Permalink
Add path variables support.
Browse files Browse the repository at this point in the history
  • Loading branch information
starlight36 committed Sep 11, 2016
1 parent ec66212 commit 44accfe
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ client.addMiddleware(request => response => {

// Fire request.
client.get('test').then(response => console.log(response.jsonData));

// Path variables support.
client.get('users/{id}', { uriParams: { id: 1 } }).then(response => console.log(response.jsonData));
```

## Asynchronous pre-request middleware
Expand Down
9 changes: 7 additions & 2 deletions modules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default class FetchHttpClient {

options = { headers: {}, ...options };

const url = this.resolveUrl(path);
const url = this.resolveUrl(path, options.uriParams || {});
const responseMiddlewares = [];
const requestPromise = this.middlewares.reduce(
(promise, middleware) => promise.then(request => {
Expand Down Expand Up @@ -79,7 +79,7 @@ export default class FetchHttpClient {
return this.request(path, 'PATCH', options);
}

resolveUrl(path) {
resolveUrl(path, variables = {}) {
if (path.toLowerCase().startsWith('http://')
|| path.toLowerCase().startsWith('https://')
|| path.startsWith('//')) {
Expand All @@ -96,6 +96,11 @@ export default class FetchHttpClient {
fullUrl = `${baseUrl}/${path}`;
}

fullUrl = fullUrl.replace(/\{(\w+)\}/ig, (match, group) => {
if (!variables[group]) throw new Error(`Unknown path variable '${group}'.`);
return encodeURIComponent(variables[group]);
});

return fullUrl;
}
}
Expand Down
13 changes: 11 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ describe('FetchHttpClient', () => {
global.fetch = () => Promise.resolve({ status: 200 });
return new FetchHttpClient('http://mydomain.com')
.addMiddleware(request => {
assert.equal(request.url, 'http://mydomain.com/test');
assert.equal(request.url, 'http://mydomain.com/test/1');
Promise.resolve('dumy-token')
.then(token => (request.options.headers.Token = token, request));
})
.addMiddleware(request => assert.equal(request.options.headers.Token, 'dumy-token'))
.addMiddleware(() => response => (response.status1 = response.status, response))
.fetch('/test', { method: 'GET' })
.fetch('/test/{id}', { method: 'GET', uriParams: { id: 1 } })
.then(response => {
assert.equal(response.status, 200);
assert.equal(response.status1, 200);
Expand Down Expand Up @@ -75,6 +75,15 @@ describe('FetchHttpClient', () => {
assert.equal('http://site.com/test/path', client.resolveUrl('http://site.com/test/path'));
assert.equal('https://site.com/test/path', client.resolveUrl('https://site.com/test/path'));
assert.equal('//site.com/test/path', client.resolveUrl('//site.com/test/path'));
assert.equal('http://mydomain.com/api/1', client.resolveUrl('api/{id}', { id: 1 }));
assert.equal('http://mydomain.com/api/1/test', client.resolveUrl('api/{id}/{name}', { id: 1, name: 'test' }));
assert.equal('http://mydomain.com/api/%E6%B1%89%E5%AD%97', client.resolveUrl('api/{name}', { name: '汉字' }));
try {
client.resolveUrl('api/{unknown}');
assert.fail('Should throw exception when a unknown variable in path.');
} catch (ex) {
assert.equal('Unknown path variable \'unknown\'.', ex.message);
}
client = new FetchHttpClient('http://mydomain.com/api');
assert.equal('http://mydomain.com/test', client.resolveUrl('/test'));
assert.equal('http://mydomain.com/api/test', client.resolveUrl('test'));
Expand Down

0 comments on commit 44accfe

Please sign in to comment.