All files / lib/util index.js

100% Statements 42/42
100% Branches 23/23
100% Functions 4/4
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 691x 1x   1x   1x   72x     79x 78x 78x 1x   77x 77x   77x 2x 2x 1x   2x     75x 120x 105x   105x 93x   12x     105x 29x       75x 29x     75x     4x 4x 20x   2x     95x     15x 15x 32x 15x 11x     11x      
const CoinpaymentsError = require(`../error`);
const schema = require(`../config/schema`);
 
const OR_OPERATOR = `|`;
 
module.exports = {
  getSchema: function(cmd) {
    return schema[cmd];
  },
  assertPayload: function({ cmd = ``, ...payload }) {
    if (!cmd) return new CoinpaymentsError(`No method passed`);
    const cmdSchema = this.getSchema(cmd);
    if (cmdSchema === undefined)
      return new CoinpaymentsError(`No such method ${cmd}`);
 
    let error = `Missing parameters: `;
    let isError = false;
 
    if (cmd === `create_mass_withdrawal`) {
      isError = !this.validateMassWithDrawal(payload);
      if (isError) {
        error = `Invalid mass withdrawal payload`;
      }
      return { isError, error };
    }
 
    for (const key in cmdSchema) {
      if (isError) break;
      const rule = cmdSchema[key];
 
      if (rule.indexOf(OR_OPERATOR) === -1) {
        isError = !this.hasOne(rule, payload);
      } else {
        isError = !this.xor(rule.split(OR_OPERATOR), payload);
      }
 
      if (isError) {
        error += `${rule}, `;
      }
    }
 
    if (isError) {
      error = new CoinpaymentsError(error.slice(0, -2));
    }
 
    return { isError, error };
  },
  validateMassWithDrawal(payload) {
    const regex = /wd\[wd[0-9]\]\[(amount|address|currency|dest_tag)\]/;
    for (const key in payload) {
      if (!regex.test(key)) return false;
    }
    return true;
  },
  hasOne: function(rule, payload) {
    return payload[rule] !== undefined;
  },
  xor: function(rules, payload) {
    let flag = false;
    for (const rule in rules) {
      if (payload[rules[rule]] !== undefined) {
        if (flag) return false;
        flag = true;
      }
    }
    return flag;
  }
};