nodejs将服务注入另一个服务

时间:2017-12-14 15:06:12

标签: node.js service controller mean-stack

目前,我有一个控制器,它使用服务填充数组,然后计算该数组的中位数。

我想要做的是,而不是在控制器内部拥有所有逻辑,我想创建一个新服务,并在该服务中进行计算。

这是我拥有的控制器,它正在工作。

var RefCompanyService = require('../services/RefCompany.service')
var math = require('mathjs');

_this = this


exports.getMedian = async function (req, res, next) {

var mxnRateList = [];
var page = req.query.page ? req.query.page : 1
var limit = req.query.limit ? req.query.limit : 10;

console.log(page, limit)

try {
    var refCompanies = await RefCompanyService.getRefCompanies({}, page, limit)

    /**Median */
    for (i = 0; i < refCompanies.docs.length; i++) {
        mxnRateList.push(refCompanies.docs[i].currency.mxn);
    }



    var median = {
        median: {
            mxn: math.median(mxnRateList),
        }
    }


    return res.status(200).json({ status: 200, data: median, message: "Succesfully Calculate Median rate" });
} catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
}
}

这是添加了median.service.js后的控制器

var MedianService = require('../services/median.service')


exports.getMedian = async function (req, res, next) {
var page = req.query.page ? req.query.page : 1
var limit = req.query.limit ? req.query.limit : 10;

console.log(page, limit)

try {
    var median = await MedianService.median();
    return res.status(200).json({ status: 200, data: median, message: "Succesfully Calculate Median rate" });
} catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
}
}

这是新服务,median.service.js

var RefCompanyService = require('./RefCompany.service')
var math = require('mathjs');
var RefCompany = require('../models/refCompany.model')

_this = this


exports.median = async function (query, page, limit) {

var mxnRateList = [];


try { // I think this is a problem
    var refCompanies = await RefCompanyService.getRefCompanies({}, page, limit)
    /**Median */
    for (i = 0; i < refCompanies.docs.length; i++) {
        mxnRateList.push(refCompanies.docs[i].currency.mxn);
    }


    /**Calculate median, High, low*/
    var median = {
        median: {
            mxn: math.median(mxnRateList)
        }
    }
    var median = 0;
    return median;

} catch (e) {
    throw Error("Error while calculating Median")
}
}

我确信我的控制器工作正常,因为我使用虚拟数据检查它并正确传递数据。 我认为给我一个问题的是这一行

var refCompanies = await RefCompanyService.getRefCompanies({}, page, limit)

在median.service.js中,所以我在这个服务中注入了另一个服务,但是当我用POSTMAN尝试它时它给了我一个错误

{
"status": 400,
"message": "Error while calculating Median"
}

我认为refCompanies无法通过服务填充它。

1 个答案:

答案 0 :(得分:1)

问题是,我必须声明并初始化这两个变量:

var page = 1
var limit = 10;