【问题标题】:How can I create a wrapper around a controller function on node.js?如何在 node.js 上围绕控制器函数创建包装器?
【发布时间】:2021-11-01 12:31:57
【问题描述】:

我的项目使用 express。我想重用当前在控制器上的一些代码。

getCustomersByCompanyId = async (req, res) => {
   ... some logic ...
}

getCustomersByCompanyId = async (req, res) => {

   const companyId = getCompanyByName(req.params.name)._id;

   // Here I want to do some kind of a wrapper around getCustomersByCompanyId
   // I have the id. But it seems that I need to send req contains that contains the id and not just the id as an argument... what's the best practice?
   return getCustomersByCompanyId(companyId); // <---- In other syntaxes I would do something like...
   
}

【问题讨论】:

  • 让函数带一个ID,并把控制器函数分开,让它根据请求调用另一个具有正确ID的函数。

标签: node.js express controller


【解决方案1】:

您始终可以创建一个包含所有可以多次使用的不同功能的服务,并在必要的时间和地点调用该服务的功能。 例如,您可以创建公司服务并创建 getCustomersByCompanyId(customerId) 函数来返回您的数据并将该函数用于:

export class companyService {
   const customersByCompanyId = companyId => {
      <----------- logic here -------------->
   }
}

那么你可以在这里使用:

getCustomersByCompanyId = async (req, res) => {
    return companyService.customersByCompanyId(req.param.companyId);
}

这里也是:

getCustomersByCompanyIdAsOtherController = async (req, res) => {

   const companyId = getCompanyByName(req.params.name)._id;
   return companyService.customersByCompanyId(companyId);   
}

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 2011-09-30
    • 2021-03-26
    • 1970-01-01
    • 2019-01-21
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多