var Spec02 = require("../../specs/spec_0_2.js");

const spec02 = new Spec02();

function JSONParser(_spec) {
  this.spec = (_spec) ? _spec : new Spec02();
}

/**
 * Level 0 of validation: is that string? is that JSON?
 */
function validate_and_parse_as_json(payload) {
  var json = payload;

  if(payload) {
    if( (typeof payload) == "string"){
      try {
        json = JSON.parse(payload);

      }catch(e) {
        throw {message: "invalid json payload", errors: e};
      }

    } else if( (typeof payload) != "object"){
      // anything else
      throw {message: "invalid payload type, allowed are: string or object"};
    }
  } else {
    throw {message: "null or undefined payload"};
  }

  return json;
}

/*
 * Level 1 of validation: is that follow a spec?
 */
function validate_spec(payload, spec) {

  // is that follow the spec?
  spec.check(payload);

  return payload;
}

JSONParser.prototype.parse = function(payload) {

  // Level 0 of validation: is that string? is that JSON?
  var valid0 = validate_and_parse_as_json(payload);

  // Level 1 of validation: is that follow a spec?
  var valid1 = validate_spec(valid0, this.spec);

  return valid1;
}

module.exports = JSONParser;

@@ -1,158 +1,28 @@
-var Spec02 = require(%22../../specs/spec_0_2.js%22);%0A%0Aconst spec02 = new Spec02();%0A%0Afunction JSONParser(_spec) %7B%0A  this.spec = (_spec) ? _spec : new Spec02();
+function JSONParser() %7B%0A
 %0A%7D%0A%0A
@@ -813,32 +813,8 @@
   //
- Level 0 of validation: 
 is t
@@ -850,17 +850,16 @@
 ar valid
-0
  = valid
@@ -895,109 +895,8 @@
 );%0A%0A
-  // Level 1 of validation: is that follow a spec?%0A  var valid1 = validate_spec(valid0, this.spec);%0A%0A
   re
@@ -905,17 +905,16 @@
 rn valid
-1
 ;%0A%7D%0A%0Amod

Remove the responsability of spec checking