Skip to content

Commit

Permalink
Adding and checking for supported encodings in util function to avoid…
Browse files Browse the repository at this point in the history
… exception (#205)

* Adding supported encodings

* Adding unit tests

* Undoing package-lock.json
  • Loading branch information
issacnitinmsft authored Mar 30, 2020
1 parent 5ce8cd7 commit da95c07
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/Util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ export function obtainContentCharset (response: IHttpClientResponse) : string {
// |__ matches would be ['charset=utf-8', 'utf-8', index: 18, input: 'application/json; charset=utf-8']
// |_____ matches[1] would have the charset :tada: , in our example it's utf-8
// However, if the matches Array was empty or no charset found, 'utf-8' would be returned by default.

const nodeSupportedEncodings = ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'binary', 'hex'];
const contentType: string = response.message.headers['content-type'] || '';
const matches: (RegExpMatchArray|null) = contentType.match(/charset=([^;,\r\n]+)/i);

return (matches && matches[1]) ? matches[1] : 'utf-8';
return (matches && matches[1] && nodeSupportedEncodings.indexOf(matches[1]) != -1) ? matches[1] : 'utf-8';
}
22 changes: 22 additions & 0 deletions test/units/httptests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,28 @@ describe('Http Tests', function () {
assert(obj.source === "nock", "request should redirect to mocked missing");
});

it('does basic http get request with server response having encoding supported by nodejs', async() => {
nock('http://microsoft.com')
.get('/')
.reply(200, 'Microsoft', {
'Content-Type': 'text/plain;charset=utf-8'
});
let res: httpm.HttpClientResponse = await _http.get('http://microsoft.com');
let body = await res.readBody();
assert(body == 'Microsoft', "response should be 'Microsoft'");
});

it('does basic http get request with server response having encoding not supported by nodejs', async() => {
nock('http://microsoft.com')
.get('/')
.reply(200, 'Microsoft', {
'Content-Type': 'text/plain;charset=us-ascii'
});
let res: httpm.HttpClientResponse = await _http.get('http://microsoft.com');
let body = await res.readBody();
assert(body == 'Microsoft', "response should be 'Microsoft'");
});

it('does not follow redirects if disabled', async() => {
nock('http://microsoft.com')
.get('/redirect-to')
Expand Down

0 comments on commit da95c07

Please sign in to comment.