Abhirock
Abhirock

Reputation: 445

Getting TypeError: FabricUserControllers is not a constructor which can not be catch

I am new to node.js and Javascript.

I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js". I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.

I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block

Please see below code

  let FabricUserControllers3 = require("./FabricUserController");

GetAllProduce: function (req, res, next) {
    try{
    let output = {};
    var resArray = new Array();
    let VZID = req.body.username;

  console.log('test', 'GetAllProduce')
  console.log('USername', VZID)

    MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
        if (err) {
            let connError = new Error(500, "Error connecting to TEST database", err);
            res.status(connError.status).json(connError);
        } else {
            let query = {};


            client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
                console.log(response);
                if (err) {
                    let roleError = new Error(500, "Error getting Produce information", err);
                    res.status(500).json(roleError);
                } else if (response.length > 0) {

                   //DO someting here 
                   //FabricUserControllers3 = {};

                   FabricUserControllers3 = new FabricUserControllers();// getting issue here
                   FabricUserControllers3.GetAll((VZID), (response) => { 
                    console.log("data result", result)

                    res.status(200).json(response);

                    client.close();
                   })

                } else {
                    output.message = "Produce doesn't exist";
                    res.status(409).json(output);

                    client.close();
                }
            });

        }

    });
}catch(e){
    if (e instanceof TypeError){
       console.log('error1', e.message);
        printError(e,true);


    }else{
        console.log("error2", e.message);
        printError(e, false);
    }
}

},

FabricUserController.js

'use strict';

const {
    FileSystemWallet,
    Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');

var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;

var client = new Client();


const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);


var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;


const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

let response = {};
class FabricUserControllers {
    constructor() {
        console.log("constructer called")
    }

    async ProduceRegistration(Username, produceid, callback) {
        // Create a new file system based wallet for managing identities.
        try {


            const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
                setTimeout(() => {
                    cb();
                    resolve();
                }, timeout);
            });

            let query2 = {}
            query2.PRODUCEID = produceid;
            // console.log('PRODUCEID',produceid)
            var PRODUCE = {};
            const walletPath = path.join(process.cwd(), 'wallet');
            const wallet = new FileSystemWallet(walletPath);
            console.log(`Wallet path: ${walletPath}`);
            console.log('Username', Username)

            // Check to see if we've already enrolled the user.
            const userExists = await wallet.exists(Username);
            if (!userExists) {
                console.log('An identity for the user:  ' + Username + ' does not exist in the wallet');
                console.log('call the registerUser before retrying');
                response.data = null;
                response.httpstatus = 400;
                response.message = `An identity for the  ${Username} does not exist in the wallet`;
                return response;
            }
            // Create a new gateway for connecting to our peer node.
            const gateway = new Gateway();
            await gateway.connect(ccpPath, {
                wallet,
                identity: Username,
                discovery: {
                    enabled: false,
                    asLocalhost: true
                }
            });
            ///
            MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
                if (err) {

                    // let connError = new Error(500, "Error connecting to TEST database", err);
                    response.data=null;
                    response.httpstatus = 500;
                    response.message =   "Error connecting to TEST database :" + err;                       
                    //  res.status(connError.status).json(connError);
                    return response;
                } else {

                    client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
                        if (err) {

                            response.httpstatus = 500;
                            response.message =   "Error with DB :" + err;           
                            return response;
                        } 


                            else{

                                console.log("blockchain_status", docs[0].blockchain_status)
                               console.log('Role name DB',docs);
                             console.log('Role name DB1',docs[0]);
                                if(docs[0].STATUS)
                            PRODUCE.produceid = docs[0].PRODUCEID;
                            PRODUCE.produceName = docs[0].PRODUCE;
                            PRODUCE.farmLocation = docs[0].FARMLOCATION;
                            PRODUCE.plantingDate = docs[0].PLANTINGDATE;
                            PRODUCE.harvestDate = docs[0].HARVESTDATE;
                            PRODUCE.status = docs[0].STATUS;
                            PRODUCE.produceQuantites = docs[0].VARIETY;
                            PRODUCE.gapInfo = docs[0].GAP;
                            PRODUCE.farmerID = docs[0].farmerID;
                            console.log('Produce', PRODUCE);

            const doStuffAsync = async () => {
                setAsyncTimeout(async () => {

                    // Get the network (channel) our contract is deployed to.
                    const network = await gateway.getNetwork('dfarmchannel');

                    // Get the contract from the network.
                    const contract = network.getContract(config1.chaincodeName);
                    var args = JSON.stringify(PRODUCE)
                    console.log("type of arg", typeof (args));
                    // Submit the specified transaction.

                    // console.log('produceID', args.produceID);

                    if(args==null || args==''){                        
                        console.log('Server not responding please try again');
                    }else
                    { 
                    const result = await contract.submitTransaction('ProduceRegistration', args);
                    var argsJson = JSON.parse(result)
                    // console.log('result', argsJson)
                    // console.log('result1', result)
                     if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
                    //     // return false;                   
                            response.data = result
                            response.httpstatus = 200;
                            response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
                            return callback(response);
                            //         console.log('result before', response);
                    // console.log('Transaction has been submitted ansd successfull with Result :' + result);             



                     }else{
                        console.log('blockchain server not responed')
                        //  return false
                         response.httpstatus = 500;
                        response.message =   `Please enter produce ID :`;           
                        return response;
                     }
                }
                }, 4000);
            };

             doStuffAsync();


            }
                        client.close();

                    })
                }
            })
            await gateway.disconnect();
        }
        catch (error) {
            // if(error) throw error;
            response.error = error;
            response.httpstatus = 500;
            response.message = "Failed to enroll admin due to above error";
            return response;
        }


    };

}
module.exports = FabricUserControllers;

Upvotes: 1

Views: 899

Answers (1)

Jose Mato
Jose Mato

Reputation: 2799

@Abhirock, on your main file you have:

let FabricUserControllers3 = require("./FabricUserController");


FabricUserControllers3 = new FabricUserControllers();// getting issue here

You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:

const FabricUserController = require("./FabricUserController");


const fabricUserControllers3 = new FabricUserController();

Hope it helps :))

Upvotes: 1

Related Questions