【问题标题】:How to use service layer in node js如何在 node js 中使用服务层
【发布时间】:2019-02-09 09:31:32
【问题描述】:

我是 Node js 的新手。我的应用程序使用了 express 和 sequelize。

这是我的路由器功能。

router.post('/add-merchant', [
    check('name').not().isEmpty(),
    check('city').not().isEmpty(),
    check('state').not().isEmpty(),
    check('country').not().isEmpty(),
], (req, res, next) => {
    try {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json({ errors: errors.array()});
        }

        var merchant = merchantService.addMerchant(req);
        return res.json(merchant)
    } catch (error) {
        return res.json({"status": "error", "message": error.message})
    }
});

我已经创建了一个名为 MercerService.js 的文件

我已经添加了用于在 MercerService.js 中插入数据的代码并尝试过这样

var merchant = merchantService.addMerchant(req);

但我无法从商家服务中获取任何数据。这是我的商家服务代码

var models = require("../models");

var merchantService = {
    addMerchant: (req) => {
        models.merchants.create(req.body).then((merchant) => {
            return merchant.dataValues
        });
    }
}

module.exports = merchantService;

我找不到问题。请帮助任何人解决此问题。

提前致谢

【问题讨论】:

  • 简单地说merchantService.addMerchant函数是对DB的异步调用,这意味着你不能使用return语句来返回数据。您需要使用回调或承诺。

标签: node.js express sequelize.js


【解决方案1】:

您正在以同步方式管理异步任务,但它不起作用。

您应该以这种方式更改您的请求处理程序:

router.post('/add-merchant', [
  check('name').not().isEmpty(),
  check('city').not().isEmpty(),
  check('state').not().isEmpty(),
  check('country').not().isEmpty(),
], (req, res, next) => {
  try {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.json({ errors: errors.array() });
    }

     merchantService.addMerchant(req).then((merchant)=>{
      res.json(merchant)
    })
  } catch (error) {
    return res.json({ "status": "error", "message": error.message })
  }
});

并像这样修复您的商家服务(请参阅return 值以启动承诺链):

const merchantService = {
  addMerchant: (req) => {
    return models.merchants.create(req.body)
      .then((merchant) => {
        return merchant.dataValues
      });
  }
}

module.exports = merchantService;

【讨论】:

  • 请注意:服务一般不应该知道 req、res 或任何 api 特定概念。最好直接将 req.body 传递给 service。这样服务就可以跨系统重用
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
相关资源
最近更新 更多