繁体   English   中英

Node.js后端API

[英]Node.js backend API

因此,即时通讯目前从以下代码重写了我的api:

function getAirplaneCompany(id) {
        return airPlaneCompany.findOne({_id: id}).then(function (firm) {
            return firm;
        });
    }

对此:

exports.getAirplaneCompany = function (req,res) {
    return airPlaneCompany.findOne({_id: id}).then(function (firm) {
        return res.json(firm);
    });
};

我可以像通常在另一个控制器中一样调用getAirplaneCompany函数吗?

例如:

exports.PlaneExpensesFromXToY = function (req,res) {
    return getAirplaneCompany(someID).then(function (response) {
        // do something with it here;
    });
};

还可以从getAirplaneCompany获取ID,这样做是否正确:

exports.getAirplaneCompany = function (req,res,id) {
    return airPlaneCompany.findOne({_id: id}).then(function (firm) {
        return res.json(firm);
    });
};

我该如何从PlaneExpensesFromXToY函数中调用它?

编辑:

计划像这样调用它: router.post('/ships/get',ships.getSpecificCompany());

编辑二:

我重新编写它并需要获取req和res的原因是因为我正在寻找一种在某些函数内发出socket.io事件的方法。

我搜索了将近一年,看来这是我必须完成的使用其中的socket.io的方法。

此外,我还阅读了有关宁静的api及其外观的信息。 例子:

router.post('/gang/garage/withdraw',gangs_model.withdrawGangCar());
router.post('/gang/garage/donate',gangs_model.donateCarToGang());

更新3:gangs_model和ships都是这样的:

var ships_model = require('./app/gamemodels/ship_model.js');

如果您需要对来自另一个控制器的呼叫和路由请求使用相同的功能,则建议如下:

function getSpecificCompany(id){
  new Promise(function(resolve, reject) {
    airPlaneCompany.findOne({_id: id})
       .then(function (firm) {
           resolve(firm);
       })
       .catch(function(err){
          reject(err);
       });
  });
}

在路线中,您将执行以下操作:

route.get('airplaneCompany/:id, getAirplaneCompany);

在路由功能中,您可以执行以下操作:

exports.getAirplaneCompany = function (req, res) {
    getSpecificCompany(req.params.id)
       .then(function(company){
            res.json(company);
       });
};

来自不同控制器的用法相同。

exports.PlaneExpensesFromXToY = function (req, res) {
    getSpecificCompany(someID).then(function (response) {
        // do something with it here;
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM