从路由器调用对象(类)上的方法的正确方法?

时间:2019-07-18 06:45:41

标签: javascript node.js

首先,我对模糊的标题表示歉意。简而言之,这就是我要实现的目标。 我必须要具备以下条件:

  1. 一个类(wallet.js)
  2. 服务GET请求的路由器(index.js)

这就是我想要做的:

在进行初始化的app.js中,我实例化了NeworkConnection类的对象:

(async () => {
    var wallet = require('./modules/wallet')(params);
})();

它在async块中,因为有一些异步调用。

现在我想做的是在router/index.js中这样的事情:

    router.get('/getBalance', function(req, res, next) {
        wallet.getBalance();
        ...
      })

我的问题是,实现这一目标的最佳方法是什么?如何将初始化后的wallet对象传递到index路由器以调用Wallet类中的方法?

谢谢。

2 个答案:

答案 0 :(得分:1)

您只需在路由/控制器文件中初始化wallet。但是这样做会导致每个用户都使用相同的钱包。因为该应用程序是单个应用程序。

因此,基本上,您需要使用session,并且对于每个会话,您都需要实例化一个钱包对象。

假设您在设置会话的路由/login

router.js

const express = require('express');

const router = express.Router();

const Wallet = require('wallet');

const wallets = {};

router.post('/login',async (req,res)=>{
  //login
  wallets[req.sessionID] = new Wallet()//or something
  //the async calls
  res.json({
    success:true
  })
});

router.get('/getBalance', auth /*to check if logged in*/, (req,res)=>{
  const wallet = wallets[req.sessionID];
  wallet.getBalance();
});

module.exports = router;

基本上,这就是您的操作方法,可作为一般方向的提示。

答案 1 :(得分:0)

忽略此

如果您真的想在一个单独的文件中实例化它们-(可能是因为您要在其他地方使用它?)我认为以下方法会起作用:

// app.js

let wallet;

(async () => {
   wallet = require('./modules/wallet')(params);
})();

module.exports = {
   wallet
}

然后仅在路由器的index.js中要求它:

// index.js
const wallet = require('./app').wallet;

router.get('/getBalance', function(req, res, next) {
    wallet.getBalance();
    ...
})

这工作

我创建了一个有效的虚拟示例。请考虑以下内容:

// wallet.js
let wallet;

class Wallet {
    constructor () {
        this.name = 'NAME!';
    }
}

// just a way to simulate the asynchronous instantiation of your wallet
async function initWallet() {
    return new Promise( (resolve, reject) => {
            if (!wallet) {
                setTimeout( () => {
                    console.log('instantiating...');
                    wallet = new Wallet();
                    resolve(wallet);
                }, 2000)
            } else {
                console.log('already exists!');
                resolve(wallet);
            }


    });
}

module.exports = {
    initWallet
}
// wallet2.js (a second file that also uses wallet. 
// This will be used to check that indeed when the function 
// initWallet is called multiple times, 
// the returned objects refer to a singleton object)
const initWallet = require('./mod').initWallet;

module.exports = {
    secondInitWallet: initWallet
};
const initWallet = require('./wallet').initWallet;
const secondInitWallet = require('./wallet2').secondInitWallet;

let wallet;

router.get('/getBalance', async function(req, res, next) {
    wallet = await initWallet();
    wallet.getBalance();
    ...
    wallet2 = await secondInitWallet();

    // just to make sure that the instantiated object is a singleton
    console.log(wallet, wallet2);
    wallet.name = 'CHANGED NAME!';
    console.log(wallet, wallet2);
})