Skip to content

Commit

Permalink
feat: add setDefaultHeaders method on base service class (#207)
Browse files Browse the repository at this point in the history
This change adds a setter for the default headers stored on the base service.
These headers are sent with every SDK request. All of the other language cores
supported setting these values post-construction so this brings Node to parity.

Signed-off-by: Dustin Popp <dpopp07@gmail.com>
  • Loading branch information
dpopp07 authored Jul 28, 2022
1 parent 0b56cf9 commit 29bec13
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions etc/ibm-cloud-sdk-core.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export class BaseService {
enableRetries(retryOptions?: RetryOptions): void;
getAuthenticator(): any;
getHttpClient(): AxiosInstance;
setDefaultHeaders(headers: OutgoingHttpHeaders): void;
setEnableGzipCompression(setting: boolean): void;
setServiceUrl(url: string): void;
}
Expand Down
14 changes: 14 additions & 0 deletions lib/base-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,20 @@ export class BaseService {
}
}

/**
* Set the HTTP headers to be sent in every request.
*
* @param {OutgoingHttpHeaders} headers The map of headers to include in requests.
*/
public setDefaultHeaders(headers: OutgoingHttpHeaders): void {
if (typeof headers !== 'object') {
// do nothing, for now
return;
}

this.baseOptions.headers = headers;
}

/**
* Turn request body compression on or off.
*
Expand Down
29 changes: 29 additions & 0 deletions test/unit/base-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,35 @@ describe('Base Service', () => {

expect(disableRetriesMock).toHaveBeenCalled();
});

it('setDefaultHeaders should override the headers object with new headers', () => {
const testService = new TestService({
authenticator: AUTHENTICATOR,
headers: {
'X-Some-Header': 'value',
},
});

testService.setDefaultHeaders({ 'X-New-Header': 'new value' });

expect(testService.baseOptions.headers['X-New-Header']).toEqual('new value');
expect(testService.baseOptions.headers['X-Some-Header']).toBeUndefined();
expect(Object.keys(testService.baseOptions.headers)).toEqual(['X-New-Header']);
});

it('setDefaultHeaders should do nothing when not given an object', () => {
const testService = new TestService({
authenticator: AUTHENTICATOR,
headers: {
'X-Some-Header': 'value',
},
});

testService.setDefaultHeaders('new header: another value');

expect(Object.keys(testService.baseOptions.headers)).toEqual(['X-Some-Header']);
expect(testService.baseOptions.headers['X-Some-Header']).toEqual('value');
});
});

function TestService(options) {
Expand Down

0 comments on commit 29bec13

Please sign in to comment.