json-api-schema
Version:
JSON Api Schema is a JSON dialect that can describe any Web Based API that uses JSON to exchange data.
174 lines (167 loc) • 3.7 kB
JavaScript
var EntityParser;
EntityParser = (function() {
function EntityParser() {
this.classes = {
Action: require("../model/action"),
Resource: require("../model/resource"),
Api: require("../model/api"),
Type: require("../model/type"),
Schema: require("../model/schema")
};
this.schema = {
Api: {
title: {
type: "Primitive"
},
description: {
type: "Primitive"
},
resources: {
type: "Map",
options: {
elems: "Resource"
}
},
types: {
type: "Map",
options: {
elems: "Type"
}
},
protocols: {
type: "Map",
options: {
elems: "Object"
}
},
actions: {
type: "Map",
options: {
elems: "Action"
}
},
events: {
type: "Map",
options: {
elems: "Event"
}
}
},
Action: {
title: {
type: "Primitive"
},
description: {
type: "Primitive"
},
params: {
type: "Schema"
},
returns: {
type: "Schema"
}
},
Event: {
title: {
type: "Primitive"
},
description: {
type: "Primitive"
},
params: {
type: "Schema"
},
returns: {
type: "Schema"
}
},
Resource: {
title: {
type: "Primitive"
},
description: {
type: "Primitive"
},
type: {
type: "Primitive"
},
resources: {
type: "Map",
options: {
elems: "Resource"
}
},
protocols: {
type: "Object"
},
actions: {
type: "Map",
options: {
elems: "Action"
}
},
events: {
type: "Map",
options: {
elems: "Event"
}
}
},
Type: {
title: {
type: "Primitive"
},
description: {
type: "Primitive"
},
schema: {
type: "Schema"
}
}
};
}
EntityParser.prototype.applySchema = function(object, type, options) {
var decl, k, klass, properties, res, schema, v;
if (options == null) {
options = {};
}
if (type === "Schema") {
return new this.classes.Schema(object);
} else if (type === "Object" || type === "Primitive") {
return object;
} else if (type === "Map") {
res = {};
for (k in object) {
v = object[k];
properties = this.applySchema(v, options.elems, {});
klass = this.classes[options.elems];
res[k] = new klass(properties);
res[k].name = k;
}
return res;
} else if (schema = this.schema[type]) {
res = {};
for (k in schema) {
decl = schema[k];
if (object[k]) {
res[k] = this.applySchema(object[k], decl.type, decl.options);
if (klass = this.classes[decl.type]) {
res[k] = new klass(res[k]);
}
} else {
if (decl.type === "Map") {
res[k] = {};
}
}
}
return res;
} else {
throw "Unexpected Parser Error. Execution should never get here.";
}
};
EntityParser.prototype.parseApi = function(object) {
return new this.classes.Api(this.applySchema(object, "Api", {}));
};
return EntityParser;
})();
module.exports = EntityParser;