如何从feathersjs钩子中分离逻辑

时间:2018-05-04 14:46:28

标签: node.js express feathersjs

有谁知道如何将路由逻辑与feathersjs钩子分开?现在,我的所有应用程序逻辑都在hook之前或之后,但我想分开它。现在我有钩子之前和之后:

module.exports = {
  before: {
    all: [
      (hook) => {
        console.log('--in before hook--')
        return hook
      }
    ]
  },
  after: {
    all: [
      (hook) => {
        console.log('--in after hook--')
        return hook;
      }
    ]
  }
};

现在我试图获得在beforeafter挂钩之间运行的逻辑。我尝试过以下方法:

尝试1 - 路由中的console.log已执行,但未执行前后挂钩。

// in jokes.service.js

app.get('/jokes', (req, res) => {
  console.log('In between before and after')
  res.json({
    msg: "SUCCESS"
  })
})

app.use('/jokes', createService(options));

const service = app.service('jokes');

service.hooks(hooks);

尝试2 - 路由中的console.log未执行,但执行了之前和之后的挂钩。

// in jokes.service.js

app.use('/jokes', createService(options));

app.get('/jokes', (req, res) => {
  console.log('In between before and after')
  res.json({
    msg: "SUCCESS"
  })
})
const service = app.service('jokes');

service.hooks(hooks);

有没有人知道如何在路由中获取两个逻辑以及在挂钩到所有执行之前和之后?

提前致谢!

1 个答案:

答案 0 :(得分:1)

custom service middleware documentation所示,可以在注册服务时添加自己的Express中间件。请记住,钩子将独立于传输(它们将通过HTTP,websockets和任何其他传输机制工作),其中Express中间件仅适用于HTTP请求。

beforeafter之间是被调用的actual service method。对于您的示例,以下内容:

const beforeMiddleware = (req, res, next) => {
  console.log('Middleware before service')
  next()
}

const afterMiddleware = (req, res, next) => {
  console.log('Middleware after service')
  next()
}

app.use('/jokes', beforeMiddleware, createService(options), afterMiddleware);

const service = app.service('jokes');

service.hooks({
  before: {
    all: [
      (hook) => {
        console.log('in before hook')
        return hook
      }
    ]
  },
  after: {
    all: [
      (hook) => {
        console.log('in after hook')
        return hook;
      }
    ]
  }
});

将打印

Middleware before service
in before hook
in after hook
Middleware after service

请求/jokes