Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect from a feathers.js service

I have a feathers.js service and I need to redirect to a specific page when using post

class Payment {
   // ..
   create(data, params) {
      // do some logic
      // redirect to an other page with 301|302

      return res.redirect('http://some-page.com');
   }
}

Is there a posibility to redirect from a feathers.js service ?

like image 799
Alexandru Olaru Avatar asked Jan 02 '23 16:01

Alexandru Olaru


2 Answers

I'm not sure how much of a good practice in feathers this would be, but you could stick a reference to the res object on feathers' params, then do with it as you please.

// declare this before your services
app.use((req, res, next) => {
    // anything you put on 'req.feathers' will later be on 'params'
    req.feathers.res = res;

    next();
});

Then in your class:

class Payment {
    // ..
    create(data, params) {
    // do some logic
    // redirect to an other page with 301|302
    params.res.redirect('http://some-page.com');

    // You must return a promise from service methods (or make this function async)
    return Promise.resolve();
    }
}
like image 166
Derpanel Avatar answered Jan 05 '23 16:01

Derpanel


Found a way to do this in a more friendly manner:

Assuming we have a custom service:

app.use('api/v1/messages', {
  async create(data, params) {
    // do your logic

    return // promise
  }
}, redirect);

function redirect(req, res, next) {
  return res.redirect(301, 'http://some-page.com');
}

The idea behind is that feathers.js use express middlewares and the logic is the following one.

If the chained middleware is an Object, then it is parsed as a service, after you can chain any number of middlewares you want.

app.use('api/v1/messages', middleware1, feathersService, middleware2)
like image 39
Alexandru Olaru Avatar answered Jan 05 '23 14:01

Alexandru Olaru