2017-09-17 39 views
0

因此,即時通訊目前正在從以下重新寫我的API:Node.js的後端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 func?

編輯:router.post('/ships/get',ships.getSpecificCompany());

編輯兩個:

原因IM重寫,並需要得到REQ和RES是因爲即時尋找一種方法來在調用它喜歡

規劃在一些函數內部發出socket.io事件。

正如我已經搜索了近一年,似乎這是我需要完成使用socket.io內的批准。

作爲補充,我讀了關於restful api的文章以及它們應該如何看。 例子:

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

更新3: gangs_model和船隻,都是一樣的:

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

好了,你想'PlaneExpensesFromXToY'和'getAirplaneCompany'與路線和內部鏈接'PlaneExpensesFromXToY'要調用'getAirplaneCompany'? – RaghavGarg

+0

@RaghavGarg是的。但是,主要問題是socket.io,即時通訊只是爲了使用socket.io而做這一切:P – maria

+0

然後,你將不得不做另一個函數,它會調用'findOne'的實際數據庫,你將從這兩個函數中訪問這個新的函數獲得單一真相的路線。 – RaghavGarg

回答

0

如果需要使用相同的功能用於將呼叫從另一個控制器和路由請求我會建議是這樣的:

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; 
    }); 
}; 
+0

router.post('/ ships/get',ships.getSpecificCompany()); 我怎樣才能在這裏做approche? – maria

+0

原因,即時計劃做到這一點,只是爲了得到它的socket.io。 – maria

+0

Route'/ ships/get /:id'不會調用getSpecificCompany(),但其路由「handler」,例如route.post('/ ships/get /:id,getShip)。注意:不是函數調用。然後在getShip中,您將調用getSpecificCompany並將req.body.params.id作爲您正在搜索的id的參數。 –