Skip to content

Commit

Permalink
Implement .urlParams
Browse files Browse the repository at this point in the history
  • Loading branch information
codeclown committed Sep 28, 2020
1 parent a3cd08a commit c7f2ff3
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 7 deletions.
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Requests are configured via method calls and each method always returns a fresh
- Understands Content-Type (decodes JSON responses by default)
- [TypeScript support](#usage-with-typescript)
- [Works on modern browsers and some older ones](#browser-support)
- [Fully tested](/test/specs) (see e.g. [requests.spec.js](/test/specs/requests.spec.js))
- [Fully tested](/test/specs) (see e.g. [requests.spec.js](/test/specs/requests.spec.js)) in real browsers, thanks to Sauce Labs

Why not use fetch, axios, jQuery, etc..? See [COMPARISON.md](COMPARISON.md).

Expand Down Expand Up @@ -86,6 +86,11 @@ request
console.error(error.response.status);
})

// ... with URL parameters
request
.get('https://example.com/api/accounts/:accountId/info')
.urlParams({ accountId: 123 })

// Make a POST request
request
.post('https://example.com/accounts')
Expand Down Expand Up @@ -166,6 +171,7 @@ The following methods are available.
- [.post(url)](#post)
- [.method(method)](#method)
- [.url(url)](#url)
- [.urlParams(object)](#urlparams)
- [.baseUrl(url)](#baseurl)
- [.query(object | string)](#query)
- [.headers(object)](#headers)
Expand Down Expand Up @@ -239,6 +245,23 @@ Sets the full URL of the request. If a query-string is present, it will override

Where `url` is a string, e.g. `'https://example.com/accounts'`.

### urlParams

Sets URL parameters which will be replaced from the URL when the request is sent.

```js
.urlParams(object)
```

Where `object` is an object.

Example:

```js
// Will make request to "/api/accounts/123/info"
request.get('/api/accounts/:accountId/info').urlParams({ accountId: 123 })
```

### baseUrl

Sets the base URL to which all subsequent request URLs will be appended.
Expand Down
22 changes: 20 additions & 2 deletions build/yea.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@
return segments.join('&');
}

function replaceUrlParams(url, params) {
for (var key in params) {
var regex = new RegExp(':' + key, 'g');
url = url.replace(regex, params[key]);
}
return url;
}

function createUrl(baseUrl, path, query) {
var url = '';
if (baseUrl) {
Expand All @@ -73,6 +81,7 @@

function mergeConfig(config, updated) {
return assign({}, config, updated, {
urlParams: assign({}, config.urlParams, updated.urlParams || {}),
headers: assign({}, config.headers, updated.headers || {}),
responseTransformers: [].concat(updated.responseTransformers || config.responseTransformers),
polyfills: assign({}, config.polyfills, updated.polyfills || {}),
Expand Down Expand Up @@ -111,6 +120,7 @@
this.utils = {
assign: assign,
toQueryString: toQueryString,
replaceUrlParams: replaceUrlParams,
createUrl: createUrl,
parsePropPath: parsePropPath,
applyPropPath: applyPropPath
Expand Down Expand Up @@ -148,6 +158,12 @@
return new YeaAjaxRequest(mergeConfig(this._config, { url: url, query: query }));
};

YeaAjaxRequest.prototype.urlParams = function urlParams(urlParams) {
var config = mergeConfig(this._config, {});
config.urlParams = assign({}, urlParams);
return new YeaAjaxRequest(config);
};

YeaAjaxRequest.prototype.baseUrl = function baseUrl(baseUrl) {
if (baseUrl === null) {
baseUrl = '';
Expand Down Expand Up @@ -370,8 +386,9 @@
}
};

var url = createUrl(config.baseUrl, config.url, config.query);
httpRequest.open(config.method, url, true);
var url = replaceUrlParams(config.url, config.urlParams);
var fullUrl = createUrl(config.baseUrl, url, config.query);
httpRequest.open(config.method, fullUrl, true);

for (var name in config.headers) {
httpRequest.setRequestHeader(name, config.headers[name]);
Expand All @@ -398,6 +415,7 @@
method: 'GET',
baseUrl: '',
url: '',
urlParams: {},
query: '',
body: '',
headers: {},
Expand Down
2 changes: 1 addition & 1 deletion build/yea.min.js

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ declare class YeaAjaxRequest implements PromiseLike<YeaResponse> {
*/
url(url: string): this;

/**
* Sets URL parameters which will be replaced from the URL when the request is sent.
*/
urlParams(urlParams: object): this;

/**
* Sets the base URL to which all subsequent request URLs will be appended.
*/
Expand Down
22 changes: 20 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@
return segments.join('&');
}

function replaceUrlParams(url, params) {
for (var key in params) {
var regex = new RegExp(':' + key, 'g');
url = url.replace(regex, params[key]);
}
return url;
}

function createUrl(baseUrl, path, query) {
var url = '';
if (baseUrl) {
Expand All @@ -73,6 +81,7 @@

function mergeConfig(config, updated) {
return assign({}, config, updated, {
urlParams: assign({}, config.urlParams, updated.urlParams || {}),
headers: assign({}, config.headers, updated.headers || {}),
responseTransformers: [].concat(updated.responseTransformers || config.responseTransformers),
polyfills: assign({}, config.polyfills, updated.polyfills || {}),
Expand Down Expand Up @@ -111,6 +120,7 @@
this.utils = {
assign: assign,
toQueryString: toQueryString,
replaceUrlParams: replaceUrlParams,
createUrl: createUrl,
parsePropPath: parsePropPath,
applyPropPath: applyPropPath
Expand Down Expand Up @@ -148,6 +158,12 @@
return new YeaAjaxRequest(mergeConfig(this._config, { url: url, query: query }));
};

YeaAjaxRequest.prototype.urlParams = function urlParams(urlParams) {
var config = mergeConfig(this._config, {});
config.urlParams = assign({}, urlParams);
return new YeaAjaxRequest(config);
};

YeaAjaxRequest.prototype.baseUrl = function baseUrl(baseUrl) {
if (baseUrl === null) {
baseUrl = '';
Expand Down Expand Up @@ -370,8 +386,9 @@
}
};

var url = createUrl(config.baseUrl, config.url, config.query);
httpRequest.open(config.method, url, true);
var url = replaceUrlParams(config.url, config.urlParams);
var fullUrl = createUrl(config.baseUrl, url, config.query);
httpRequest.open(config.method, fullUrl, true);

for (var name in config.headers) {
httpRequest.setRequestHeader(name, config.headers[name]);
Expand All @@ -398,6 +415,7 @@
method: 'GET',
baseUrl: '',
url: '',
urlParams: {},
query: '',
body: '',
headers: {},
Expand Down
3 changes: 3 additions & 0 deletions test/server/helper-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ app.get('/dump-headers', function (req, res) {
return "".concat(name, ": ").concat(req.headers[name]);
}).join('\n'));
});
app.get('/dump-url/*', function (req, res) {
return res.send(req.originalUrl);
});
app.get('/dump-query', function (req, res) {
return res.send(Object.keys(req.query).sort().map(function (key) {
return "".concat(key, ": ").concat(req.query[key]);
Expand Down
29 changes: 28 additions & 1 deletion test/specs/methods.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ describe('Methods', function () {
describe('defaults', function () {
it('has defaults', function () {
var defaults = yea.toObject();
expect(defaults).to.have.keys(['method', 'baseUrl', 'url', 'query', 'body', 'headers', 'responseTransformers', 'allowedStatusCode', 'timeout', 'prop', 'polyfills']);
expect(defaults).to.have.keys(['method', 'baseUrl', 'url', 'urlParams', 'query', 'body', 'headers', 'responseTransformers', 'allowedStatusCode', 'timeout', 'prop', 'polyfills']);
expect(defaults.method).to.equal('GET');
expect(defaults.baseUrl).to.equal('');
expect(defaults.url).to.equal('');
expect(defaults.urlParams).to.deep.equal({});
expect(defaults.query).to.equal('');
expect(defaults.body).to.equal('');
expect(defaults.headers).to.deep.equal({});
Expand Down Expand Up @@ -127,6 +128,32 @@ describe('Methods', function () {
});
});

describe('.urlParams', function () {
it('sets urlParams', function () {
expect(yea.urlParams({ super: 'yes' }).toObject().urlParams).to.deep.equal({ super: 'yes' });
expect(yea.urlParams({ SUPER: 'yes' }).toObject().urlParams).to.deep.equal({ SUPER: 'yes' });
});

it('overwrites existing urlParams', function () {
var req = yea.urlParams({ super: 'yes', foo: 'sir' });
expect(req.urlParams({ foo: 'bar', fresh: 'sure' }).toObject().urlParams).to.deep.equal({ foo: 'bar', fresh: 'sure' });
});

it('leaves no references', function () {
var urlParams = { super: 'yes' };
var req = yea.urlParams(urlParams);
expect(req.toObject().urlParams).to.not.equal(urlParams);
urlParams.super = 'modified';
expect(req.toObject().urlParams.super).to.equal('yes');
});

it('is immutable', function () {
var req = yea.urlParams({ super: 123 });
expect(req).to.not.equal(yea);
expect(req.constructor).to.equal(yea.constructor);
});
});

describe('.baseUrl', function () {
it('sets baseUrl', function () {
expect(yea.baseUrl('http://example.com').toObject().baseUrl).to.equal('http://example.com');
Expand Down
12 changes: 12 additions & 0 deletions test/specs/requests.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,18 @@ describe('Requests', function () {
});
});

it('replaces urlParams if present', function () {
return yea
.url('/dump-url/:accountId')
.urlParams({ accountId: 123 })
.send()
.then(function (response) {
expect(response.status).to.equal(200);
expect(response.body).to.be.a('string');
expect(response.body).to.equal('/dump-url/123');
});
});

it('sends body', function () {
return yea
.method('post')
Expand Down
14 changes: 14 additions & 0 deletions test/specs/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ describe('utils', function () {
});
});

describe('.replaceUrlParams', function () {
it('replaces param placeholders in URL', function () {
expect(yea.utils.replaceUrlParams('', {})).to.equal('');
expect(yea.utils.replaceUrlParams('http://example.com', {})).to.equal('http://example.com');
expect(yea.utils.replaceUrlParams('/accounts', {})).to.equal('/accounts');
expect(yea.utils.replaceUrlParams('/accounts/:accountId', {})).to.equal('/accounts/:accountId');
expect(yea.utils.replaceUrlParams('/accounts/:accountId', { accountId: 123 })).to.equal('/accounts/123');
expect(yea.utils.replaceUrlParams('/accounts/:accountId/info', { accountId: 123 })).to.equal('/accounts/123/info');
expect(yea.utils.replaceUrlParams('/accounts/:account-id', { 'account-id': 123 })).to.equal('/accounts/123');
expect(yea.utils.replaceUrlParams('/accounts/:AccountId', { 'accountId': 123 })).to.equal('/accounts/:AccountId');
expect(yea.utils.replaceUrlParams('/:repeat/:repeat', { repeat: 123 })).to.equal('/123/123');
});
});

describe('.createUrl', function () {
it('creates URL from baseUrl, path and query', function () {
expect(yea.utils.createUrl('', 'accounts')).to.equal('accounts');
Expand Down

0 comments on commit c7f2ff3

Please sign in to comment.