John Grayson
John Grayson

Reputation: 1496

How to separate logic from feathersjs hooks

Does anyone understand how to separate route logic from feathersjs hooks? Right now, all of my app logic is in a feathersjs before or after hook, but i'd like to separate that. Right now I have before and after hooks:

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

Now I am trying to get logic that runs between the before and after hooks. I have tried the following:

Attempt 1 - the console.log in the route was executed, but the before and after hooks were not executed.

// 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);

Attempt 2 - the console.log in the route did not execute, but the before and after hooks were executed.

// 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);

Does anyone know how I can get both logic in the route AND before and after hooks to all execute?

Thanks in advance!

Upvotes: 0

Views: 133

Answers (1)

Daff
Daff

Reputation: 44215

As shown in the custom service middleware documentation it is possible to add your own Express middleware when registering the service. Keep in mind that hooks will be transport independent (they will work through HTTP, websockets and any other transport mechanisms) where Express middleware only applies to HTTP requests.

Between before and after is the actual service method that is being called. For your example, the following:

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;
      }
    ]
  }
});

Will print

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

When requesting /jokes.

Upvotes: 1

Related Questions