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 Content-length on httpApiCall #250

Merged
merged 10 commits into from
Apr 26, 2024
14 changes: 10 additions & 4 deletions lib/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,19 @@ const intToIp = (int) => {
return octets.join('.');
};

const httpApiCall = async (url, { method = 'POST', headers = {}, body }) => {
const customHeaders = ({ headers = {}, body }) => {
const mimeType = 'application/json';
const custom = { 'Content-Type': mimeType, ...headers };
if (body) headers['Content-Length'] = Buffer.byteLength(body);
if (body) custom['Content-Length'] = Buffer.byteLength(body);
return custom;
};

const httpApiCall = async (url, { method = 'POST', headers = {}, body }) => {
const custom = customHeaders({ headers, body });
const options = { method, headers: custom, body };
return await fetch(url, options).then(async (res) => {
return await fetch(url, options).then((res) => {
const code = res.status;
if (code === 200) return await res.json();
if (code === 200) return res.json();
const dest = `for ${method} ${url}`;
throw new Error(`HTTP status code ${code} ${dest}`);
});
Expand All @@ -51,4 +56,5 @@ module.exports = {
ipToInt,
intToIp,
httpApiCall,
customHeaders,
};
14 changes: 14 additions & 0 deletions test/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,17 @@ metatests.test('Newtork: httpApiCall', async (test) => {

test.end();
});

metatests.test('Network: customHeaders', (test) => {
const body = '{"key": "value"}';
const headers = { 'Custom-Header': 'custom-value' };

const custom = metautil.customHeaders({ headers, body });

test.strictSame(typeof custom, 'object');
test.strictSame(custom['Content-Type'], 'application/json');
test.strictSame(custom['Custom-Header'], 'custom-value');
test.strictSame(custom['Content-Length'], Buffer.byteLength(body));

test.end();
});
Loading