I have the following code:
'use strict';
const Request = require('request');
class CryptoKetHandlers {
static async coins(ctx) {
try {
var CONTENT_TYPE = 'application/json';
console.log(`## Hitting cryptoket coins api for coins list ...`);
var res = await Request.get({
url: 'https://api.cryptoket.io/info/currencies',
headers: {
'Content-Type': CONTENT_TYPE,
}
}, (err, res, body) => {
//console.log(`Inside response ... res: ${res} err: ${err} body: ${body}`);
if (err) {
console.log(`#### ERROR :: API RESP :: CryptoKetHandlers :: coins :: exception :: ${err}`);
ctx.throw(500);
} else {
let res = {};
res.body = body;
res.status = 200;
return res;
}
});
} catch (ex) {
console.log(`#### ERROR :: CryptoKetHandlers :: coins :: exception :: ${ex}`);
ctx.throw(500);
}
console.log(`######### Final Response :: status - ${res.status} body - ${res.body} res :: ${res}`);
ctx.body = res;
ctx.status = 200;
}
}
module.exports = CryptoKetHandlers;
I am from Java background and new to koa & nodejs so wondering if how can I achieve the following things:
- Why res.status and res.body always return undefined?
- How can I declare CONTENT_TYPE as a class variable should be const & static?
What is want to achieve is:
Return all these err, res, body parameters from Request.get and
process it somewhere else (in another class function).- Make all the reusable variable class level so that no need to define again & again.
- If you have some suggestions to make my code more robust and cleaner.
I tried various ways by googling but no success so asking here.
Thanks in advance.