Skip to content
This repository has been archived by the owner on Jan 14, 2022. It is now read-only.

Commit

Permalink
Merge pull request #810 from LiskHQ/807-cannot-read-status-code-of-un…
Browse files Browse the repository at this point in the history
…defined

Avoid crash when response not present - Closes #807
  • Loading branch information
MichalTuleja authored Sep 7, 2018
2 parents 2b99197 + 688c5a6 commit 0d73547
Showing 1 changed file with 33 additions and 28 deletions.
61 changes: 33 additions & 28 deletions lib/api/blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,31 @@ module.exports = function (app) {
};
}

function getDelegateCall(publicKey, cb) {
if (!publicKey) {
return cb('Missing/Invalid publicKey parameter');
}

let errorMessage = null;
let delegate = null;

return request.get({
url: `${app.get('lisk address')}/delegates?publicKey=${publicKey}`,
json: true,
}, (err, response, body) => {
const statusCode = response && response.statusCode;
const responseData = body && body.data;

if (err || statusCode !== 200) {
errorMessage = err || 'Response was unsuccessful';
} else if (Array.isArray(responseData) && responseData.length > 0) {
delegate = delegatesMapper(responseData[0]);
}

return cb(errorMessage, delegate);
});
}

function Blocks() {
this.offset = function (n) {
n = parseInt(n, 10);
Expand All @@ -104,19 +129,12 @@ module.exports = function (app) {
return n;
};

this.getDelegate = function (result, cb) {
const block = result;
this.getDelegate = function (block, cb) {
const { generatorPublicKey } = block;

return request.get({
url: `${app.get('lisk address')}/delegates?publicKey=${block.generatorPublicKey}`,
json: true,
}, (err, response, body) => {
if (response.statusCode === 200 && body && Array.isArray(body.data) && body.data[0]) {
block.delegate = delegatesMapper(body.data[0]);
} else {
block.delegate = null;
}
return cb(null, result);
getDelegateCall(generatorPublicKey, (err, delegate) => {
block.delegate = delegate;
return cb(null, block);
});
};

Expand Down Expand Up @@ -214,24 +232,11 @@ module.exports = function (app) {
});
};

/* eslint-disable consistent-return */
this.getDelegate = function (result, cb) {
if (!result.block) {
return cb(null, result);
}
const block = result.block;
const { block } = result;

request.get({
url: `${app.get('lisk address')}/delegates?publicKey=${block.generatorPublicKey}`,
json: true,
}, (err, response, body) => {
if (err || response.statusCode !== 200) {
return cb(err || 'Response was unsuccessful');
} else if (body && Array.isArray(body.data) && body.data.length > 0) {
block.delegate = delegatesMapper(body.data[0]);
} else {
block.delegate = null;
}
return getDelegateCall(block.generatorPublicKey, (err, delegate) => {
block.delegate = delegate;
return cb(null, result);
});
};
Expand Down

0 comments on commit 0d73547

Please sign in to comment.