Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(headers): fixed & optimized clear method; #5507

Merged
merged 14 commits into from
Jan 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.d.cts
Expand Up @@ -33,7 +33,7 @@ declare class AxiosHeaders {

delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;

clear(): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;

normalize(format: boolean): AxiosHeaders;

Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Expand Up @@ -28,7 +28,7 @@ export class AxiosHeaders {

delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;

clear(): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;

normalize(format: boolean): AxiosHeaders;

Expand Down
16 changes: 14 additions & 2 deletions lib/core/AxiosHeaders.js
Expand Up @@ -174,8 +174,20 @@ class AxiosHeaders {
return deleted;
}

clear() {
return Object.keys(this).forEach(this.delete.bind(this));
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;

while (i--) {
const key = keys[i];
if(!matcher || matchHeaderValue(this, this[key], key, matcher)) {
delete this[key];
deleted = true;
}
}

return deleted;
}

normalize(format) {
Expand Down
20 changes: 20 additions & 0 deletions test/unit/core/AxiosHeaders.js
Expand Up @@ -236,6 +236,26 @@ describe('AxiosHeaders', function () {
});
});

describe('clear', ()=> {
it('should clear all headers', () => {
const headers = new AxiosHeaders({x: 1, y:2});

headers.clear();

assert.notDeepStrictEqual(headers, {});
});

it('should clear matching headers if a matcher was specified', () => {
const headers = new AxiosHeaders({foo: 1, 'x-foo': 2, bar: 3});

assert.notDeepStrictEqual(headers, {foo: 1, 'x-foo': 2, bar: 3});

headers.clear(/^x-/);

assert.notDeepStrictEqual(headers, {foo: 1, bar: 3});
});
});

describe('toJSON', function () {
it('should return headers object with original headers case', function () {
const headers = new AxiosHeaders({
Expand Down