Skip to content

Commit

Permalink
refactor: extract request logic into a helper module for easier mocking
Browse files Browse the repository at this point in the history
  • Loading branch information
vsetka committed Sep 9, 2017
1 parent e1e59f6 commit 21050e3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
25 changes: 9 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const languages = require('./languages');
const https = require('https');
const requestHelper = require('./request-helper');

const DEEPL_HOSTNAME = 'www.deepl.com';
const DEEPL_ENDPOINT = '/jsonrpc';
Expand Down Expand Up @@ -27,20 +27,13 @@ function translate(text, targetLanguage, sourceLanguage = 'auto') {
const postBody = getPostBody(text, targetLanguage, sourceLanguage);
const options = getRequestOptions(postBody);

const req = https.request(options, res => {
res.setEncoding('utf8');
res.on('data', body => {
try {
resolve(parseResponse(body));
} catch (exception) {
reject(new Error(`Unexpected error when parsing body: ${body}`));
}
});
requestHelper(options, postBody).then(response => {
try {
resolve(transformResponse(response));
} catch (exception) {
reject(new Error(`Unexpected error when parsing response body: ${JSON.stringify(response)}`));
}
});

req.on('error', reject);
req.write(JSON.stringify(postBody));
req.end();
}
});
}
Expand Down Expand Up @@ -82,14 +75,14 @@ function getRequestOptions(postBody) {
};
}

function parseResponse(response) {
function transformResponse(response) {
const {
result: {
target_lang: targetLanguage,
source_lang: resolvedSourceLanguage,
translations: [{ beams: [{ postprocessed_sentence: translation }] }],
},
} = JSON.parse(response);
} = response;

return {
targetLanguage,
Expand Down
14 changes: 14 additions & 0 deletions request-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const https = require('https');

module.exports = (options, postBody) => {
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
res.setEncoding('utf8');
res.on('data', body => resolve(JSON.parse(body)));
});

req.on('error', reject);
req.write(JSON.stringify(postBody));
req.end();
});
};

0 comments on commit 21050e3

Please sign in to comment.