Last active
December 14, 2015 13:39
-
-
Save ainthek/5095320 to your computer and use it in GitHub Desktop.
json-schema, generator (dojo, AMD)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define([ | |
"dojo/date/stamp", | |
"dojo/_base/lang" | |
], function(dates, lang) { | |
// summary: | |
// very first draft of obj2json-schema generator | |
var DEFAULT_OPTIONS = { | |
numberInteger : true, | |
numberPositive : false, //sets minimum to 0 for positive numbers | |
numberJsMinMax : false, //TODO: implement ranges | |
dateTimeNative : true, | |
dateTimeIsoString : true, | |
namingConventions : false | |
}; | |
function getType(o) { | |
//https://github.com/garycourt/JSV/blob/master/lib/jsv.js | |
// TODO: optimize | |
return o === undefined ? "undefined" : (o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase()); | |
} | |
function traverse(v, k, s, opts) { | |
opts = lang.mixin({}, DEFAULT_OPTIONS, opts); | |
/*jshint expr:true */ | |
s || (s = {}); | |
var t = s.type = getType(v); | |
if (t === "array") { | |
var items = s.items = {}; | |
if (v[0] != null) { | |
traverse(v[0], "items", items, opts); | |
} | |
} else if (t === "object") { | |
var props = s.properties = {}; | |
for ( var p in v) { | |
traverse(v[p], p, props[p] = {}, opts); | |
} | |
} | |
//TODO: how to make this extendable, beyond options, only example in unit-test, | |
// do not put this into code here !!! (aspect ?, beware recursion) | |
else if (t === "number") { | |
if (opts.numberInteger && v % 1 === 0) { | |
s.type = "integer"; | |
} | |
if (opts.numberPositive && v > 0) { | |
s.minimum = 0; | |
} | |
} else if (t === "date") { //extreme condition from real native object, not JSON.parse-d object | |
if (opts.dateTimeNative) { | |
s.type = "string"; | |
s.format = "date-time"; | |
} else { | |
s.type = "object"; | |
} | |
} else if (t === "string") { | |
if (opts.dateTimeIsoString) { | |
var d = dates.fromISOString(v);//TODO: detect more precise type, do i need stamp.js ? | |
if (d) { | |
s.type = "string"; | |
s.format = "date-time"; | |
} | |
} | |
} else if (opts.namingConventions) { | |
opts.namingConventions(v, k, s, opts); | |
} | |
return s; | |
} | |
function object2Schema(value, options) { | |
return traverse(value, null, {}, options); | |
} | |
object2Schema._getType = getType; //just for unit tests, not ment to be used | |
object2Schema.DEFAULT_OPTIONS = DEFAULT_OPTIONS; | |
return object2Schema; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment