all files / ErrorHandling/utility/ ResponseEntity.js

97.44% Statements 38/39
96.67% Branches 29/30
100% Functions 2/2
97.37% Lines 37/38
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68        11×   11×   10×       10× 10×   10×   10×               10×                          
'use strict';
 
var constants = require('../constants');
var config = require('../config/ErrorObject');
 
var store = {};
 
store.createResponse = function (module_name, code, data, error, callback) {
  var response = {};
 
  if ((code == null || code == undefined) && (error == null || error == undefined)) {
       throw new Error("Please Send code or error message");
  }
  else if (code == null || code == undefined) {
    if (error.name === constants.SEQUELIZE_DATABASE_ERROR_NAME)
      code = constants.SEQUELIZE_DATABASE_ERROR;
    else if (error.name === constants.SEQUELIZE_VALIDATION_ERROR_NAME)
      code = constants.SEQUELIZE_VALIDATION_ERROR;
    else if (error.name === constants.CASSANDRA_VALIDATION_ERROR_NAME)
      code = constants.CASSANDRA_VALIDATION_ERROR;
    else
      code = constants.UNDEFINED_ERROR
  }
 
  response.code = module_name + '-' + code;
  response.message = config.getMessage(code);
 
  if (error != null) response.error = error;
 
  if (data != null) {
    var isValidFlag = store.isValidJson(data);
    if (isValidFlag) {
      if (!data.hasOwnProperty('rows')) {
        response.data = data;
      }
      else {
        response.count = data.count;
        response.data = data.rows;
      }
    }
    else {
      code = constants.INVALID_JSON_OBJECT;
      response.message = config.getMessage(code);
      response.code = module_name + '-' + code;
    }
  }
  callback(response);
}
 
store.isValidJson=function (item) {
    item = typeof item !== "string"
        ? JSON.stringify(item)
        : item;
 
    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }
 
    Eif (typeof item === "object" && item !== null) {
        return true;
    }
 
    return false;
}
 
module.exports = store;