0

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:

  1. Why res.status and res.body always return undefined?
  2. 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.

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19

1 Answers1

0
  1. Why res.status and res.body always return undefined?

Firstly, Request.get() should return a Promise to work for the await to work.

The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

Second, You're accidentally replacing return value res with the other res in (err, res, body) => {}. Instead, we can return the return value as plain objects.

Making those changes,

'use strict';

let request = require('request');

const CONTENT_TYPE = 'application/json';

function makeRequest() {
  return new Promise((resolve, reject) => {
    request.get({
      url: 'https://api.cryptoket.io/info/currencies',
      headers: {
        'Content-Type': CONTENT_TYPE,
      }
    }, (err, res, body) => {
      if (err) {
        console.log(`#### ERROR :: API RESP :: CryptoKetHandlers :: coins :: exception :: ${err}`);
        return reject(err);
      }

      // return as object
      return resolve({ 
        body: body,
        status: 200
      });
    });
  });
}

class CryptoKetHandlers {

  static async coins(ctx) {
    try {
      console.log(`## Hitting cryptoket coins api for coins list ...`);
      let res = await makeRequest();
      console.log(`######### Final Response :: status - ${res.status} body - ${res.body} res :: ${res}`);
    } catch (ex) {
      console.log(`#### ERROR :: CryptoKetHandlers :: coins :: exception :: ${ex}`);
    }
  }

}

Since I replaced var with let. I've moved the final logging within tryblock.

  1. How can I declare CONTENT_TYPE as a class variable should be const & static?

The proposal for this is now underway. You can check ES6 class variable alternatives for more information.

Sridhar
  • 11,466
  • 5
  • 39
  • 43