all files / ErrorHandling/utility/ ResponseEntity.js

73.17% Statements 30/41
75% Branches 24/32
50% Functions 1/2
72.5% Lines 29/40
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 69 70        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 Iif (error.name === constants.SEQUELIZE_FOREIGN_KEY_CONSTRAINT_ERROR_NAME)
      code = constants.SEQUELIZE_FOREIGN_KEY_CONSTRAINT_ERROR;
    else if (error.name === constants.CASSANDRA_VALIDATION_ERROR_NAME)
      code = constants.CASSANDRA_VALIDATION_ERROR;
    else 
      code = constants.UNDEFINED_DATABASE_ERROR;
  }
 
  response.code = module_name + '-' + code;
  response.message = config.getMessage(code);
 
  if (error != null) response.error = error;
 
  if (data != null) {
    var isValidFlag = true;//store.isValidJson(data);
    Eif (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;
    }
 
    if (typeof item === "object" && item !== null) {
        return true;
    }
 
    return false;
}
 
module.exports = store;