How to process a JSON in the event of a request-promise failure?

2

I have 2 microservices, one in NodeJS and one in Spring. The NodeJS contains the event domain (parties, birthdays, etc.) and the Java user domain.

When querying the NodeJS event endpoints, I also query the user endpoints and add the equivalent results in a single response - abstracting the second API.

The idea is that the NodeJS microservice works independently of the micro-service written in Java. My problem is in implementing the code in NodeJS, to handle the case where the second microservice (Java) is unavailable.

var request = require('request-promise');
const Evento = require('./evento')
const url_api_externa = "http://localhost:8080/usuarios/"

Evento.methods(['get', 'post', 'put', 'delete'])
Evento.updateOptions({ new: true, runValidators: true })

Evento.after('get', function (req, res, next) {
  var eventos = res.locals.bundle
  var url = url_api_externa
  var path = req.path

  path = path.replace('/eventos', '')
  path = path.replace('/', '')

  if (path != '') {
    url = url + res.locals.bundle.idCriador
  }

  consultaExterna(url).then(function (body) {
    res.json({ eventos, criadores: body })
  }
    , function (err) {
      console.error("Falha ao trazer dados do microserviço:" + err);
      next()
    });
});

Evento.before('post', function (req, res, next) { hasUsuario(req, res, next); });
Evento.before('put', function (req, res, next) { hasUsuario(req, res, next); });

function hasUsuario(req, res, next) {
  var url = url_api_externa + req.body.idCriador

  //Só prossegue com a requisição/ação se o idCriador for equivalente a um usuário existente na API externa
  consultaExterna(url).then(function (body) {
    next();
  }, function (error, res) {

    var erroAPIExterna = {
      mensagemDesenvolvedor: "Microserviço externo indisponível",
      status: 404,
      titulo: "O módulo de usuários não está disponível no momento, tente mais tarde"
    }

    if (res != null) {
      erroAPIExterna = error.error
    }

    console.error("Erro:" + error);
    res.status(erroAPIExterna.status).json({ erro: erroAPIExterna.titulo });
  });
}

function consultaExterna(url) {
  return request({
    'method': 'GET',
    'uri': url,
    'json': true,
    'headers': {
      'User-Agent': 'MicroserviceNodeJS'
    }
  });
}

module.exports = Evento

At line 51 I display the messages api java error in api nodejs - if it occurs. But when the java service is unavailable I should be able to send the default message of unavailability to my NodeJS api and this is where my problem starts because they are in a promise that failed, so my response is null and my error is not zero (econrefused bláblá).

What I would need to do is to send the request that is one level above (the NodeJS) and not the one that failed, triggering the error in response. Something similar to next (). Json ({error}), where next () is my NodeJS request that is being processed and should deliver my message.

Any guess how to solve / implement this?

    
asked by anonymous 28.10.2017 / 20:36

0 answers