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

Set encoding according to content-type charset #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const debug = require('debug')('api-gateway');

const ua = require('./ua');
const Base = require('./base');
const { fetchPropertyFromHeader } = require('./util');

const form = 'application/x-www-form-urlencoded';
const hasOwnProperty = function (obj, key) {
Expand Down Expand Up @@ -191,8 +192,9 @@ class Client extends Base {
throw err;
}

var result = await httpx.read(response, 'utf8');
var contentType = response.headers['content-type'] || '';
const charset = fetchPropertyFromHeader(contentType, 'charset') || 'utf8';
var result = await httpx.read(response, charset);
if (contentType.startsWith('application/json')) {
result = JSON.parse(result);
}
Expand Down
19 changes: 19 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

function fetchPropertyFromHeader(headerStr, key) {
const values = headerStr.split(';') || [];
let result;
values.some((pair) => {
const kv = pair.trim().split('=');
if(kv.length === 2 && kv[0] === key) {
result = kv[1];
return true;
}
return false;
});
return result;
}

module.exports = {
fetchPropertyFromHeader
};
12 changes: 12 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const expect = require('expect.js');
const { fetchPropertyFromHeader } = require('../lib/util');

describe('util', function () {
it('should be target charset', async function () {
expect('binary').to.be.eql(fetchPropertyFromHeader('application/json; charset=binary', 'charset'));
expect(undefined).to.be.eql(fetchPropertyFromHeader('application/json;', 'charset'));
expect('utf-8').to.be.eql(fetchPropertyFromHeader('application/json;charset=utf-8;', 'charset'));
});
});