Skip to content
Snippets Groups Projects
Commit d0ee2428 authored by Lars Trieloff's avatar Lars Trieloff Committed by GitHub Enterprise
Browse files

Merge pull request #23 from ankaur/refs

Issues #17 #18 #20
parents 1b8a1204 f709a2a9
Branches
Tags
No related merge requests found
......@@ -28,6 +28,7 @@ $ node index.js
# Usage: node index.js
#
# Options:
# -d, --input path to directory containing all JSON Schemas or a single JSON Schema file. This will be considered as the baseURL [required]
# -f, --isFile pass if input is a single file path
# -o, --out path to output directory (default: ./out)
......
lib/main.js 100644 → 100755
......@@ -22,48 +22,13 @@ var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var _ = require('lodash');
var async = require('async');
var ejs = require('ejs');
var logger = require('winston');
var mkdirp = Promise.promisify(require('mkdirp'));
var readdirp = require('readdirp');
var validUrl = require("valid-url");
var Schema = require('./schema');
var Ajv = require('ajv');
var ajv = new Ajv({ allErrors: true , messages:true});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
function writeFile(outputDir, fileName, data) {
if(!fs.existsSync(outputDir)){
return mkdirp(outputDir).then((err)=>{
return fs.writeFileAsync(path.join(outputDir, fileName), data);
})
}
else {
return fs.writeFileAsync(path.join(outputDir, fileName), data);
}
}
function generateMarkdown(filename, schema) {
schema.metaElements = metaElements;
var ctx = {
schema: schema,
_: _,
validUrl: validUrl,
};
ejs.renderFile(path.join(__dirname,'../templates/md/topSchema.ejs'), ctx , { debug: false },function(err,str){
if(err)
console.error(err);
return writeFile(path.join(path.join(outDir), path.dirname(filename.substr(schemaPath.length))), path.basename(filename).slice(0, -5)+ '.md', str);
})
}
function generateNewSchemaFiles(filename, schema) {
return writeFile(path.join(path.join(outDir,"_newSchema"), path.dirname(filename.substr(schemaPath.length))), path.basename(filename), JSON.stringify(schema, null, 4));
}
// parse/process command line arguments
......@@ -87,7 +52,7 @@ var argv = require('optimist')
if (!argv.d) {
process.exit(1);
}
var schemaPathMap={};
var schemaPath = path.resolve(argv.d);
var fileDir=schemaPath;
var baseName = path.basename(schemaPath).replace(/\.[^/.]+$/, '');
......@@ -107,7 +72,7 @@ if (argv.m) {
else {
var meta=(argv.m).split("=");
if(meta.length == 2)
metaElements[meta[0]]=meta[1];
metaElements[meta[0]]=meta[1];
}
}
......@@ -119,13 +84,31 @@ var baseURL = path.resolve(fileDir);
logger.info('output directory: %s', outDir);
logger.info('processing %s...', schemaPath);
var readSchemaFiles=function(fullpath){
return fs.readFileAsync(fullpath).then((data)=>{
let schema = JSON.parse(data);
let obj = {};
obj.filePath = fullpath;
obj.jsonSchema = schema;
if(schema["$id"] && schema["$id"].length > 0){
if(! schemaPathMap[schema["$id"]])
schemaPathMap[schema["$id"]] = obj;
// TODO err
//TODO check Missing Specific properties to throw warning // function for warning
}
else {
schemaPathMap[fullpath] = obj;
}
})
}
//Function to generate Markdown for all files in a folder
var GenerateForAllFiles = function (dirname) {
var files=[];
return new Promise((resolve,reject) => {
readdirp({ root: dirname, fileFilter: '*.schema.json' })
.on('data',(entry) => {
files.push( entry.fullPath );
ajv.addSchema(require(entry.fullPath),entry.fullPath);
})
.on('end',()=>resolve(files))
......@@ -134,22 +117,22 @@ var GenerateForAllFiles = function (dirname) {
})
}).then((schemaFiles) => {
Schema.setAjv(ajv);
return Promise.map(schemaFiles,function(file){
return Schema.load( file , baseURL)
.then((processedSchemas) => {
if(argv.s)
return Promise.all([generateMarkdown(file,processedSchemas.mSchema),
generateNewSchemaFiles(file,processedSchemas.wSchema)
]);
else
return generateMarkdown(file,processedSchemas.mSchema);
})
Schema.setSchemaPathMap(schemaPathMap);
return Promise.map(schemaFiles,readSchemaFiles)
.then(() => {
logger.info("Read Schema files!!!")
return Schema.load(schemaPathMap,schemaPath,outDir,metaElements)
// .then(()=>{
// console.log(data);
// })
})
})
}
if(argv.f){
//generating markdown for a single file
Schema.load( schemaPath , baseURL)
.then((processedSchemas) => {
if(argv.s)
......
......@@ -23,45 +23,342 @@ var path = require('path');
var _ = require('lodash');
var logger = require('winston');
var readdirp = require('readdirp');
var consts = require('./constants');
var url = require("url");
var Promise=require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var jsonSchemaRefParser = require("json-schema-ref-parser");
var Writer=require('./writeFiles');
var deff='#/definitions/';
var absUrlRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
var pointer = require('json-pointer');
var smap; //TODO remove global
var sPath;
var wmap={};
var async = require('async');
function get$refType(refValue){
var startpart = "", endpart = "", refType = "";
var arr = refValue.split("#");
if(arr.length > 1)
endpart=arr[1]
var Schema=function(ajv){
this._ajv = ajv;
startpart=arr[0]
//TODO yRelNoDef
//relative-- yRelWithDef, yRelNoDef,
//absolute-- yAbsWithDef, yAbsFSchema, yAbsWithFragment
var refType="",currStartId;
var traversedRefMap;
var deff='/definitions/';
//if( absUrlRegex.test(refVal) ){
if(startpart.length > 1){
if(startpart in smap){
if(endpart.startsWith(deff)){
refType = "yAbsWithDef"
}
else{
if(endpart.length == 0)
refType = "yAbsFSchema"
else
refType = "yAbsWithFragment"
}
}
}
else {
if(endpart.startsWith(deff)){
refType = "yRelWithDef"
}
}
// }
return {startpart,endpart,refType}
}
function normaliseLinks(obj,refArr){
let basepath = refArr.startpart ;
let $linkVal = "", $linkPath = "";
if(basepath in smap){
let newpath = path.relative(path.dirname(sPath),smap[basepath].filePath).replace(/\\/g, '/'); //to cater windows paths
let temp = newpath.slice(0, -5).split("/");
$linkVal = obj["title"] ? obj["title"] : path.basename(newpath).slice(0, -5);
$linkPath = temp.join("/")+".md";
return { $linkVal , $linkPath };
}
}
function processSchema(schema){
var propertyMap={};
return new Promise((resolve,reject)=>{
if(!schema.properties)
schema.properties={}
var $id = schema["$id"] || schema["id"];
var base$id = $id;
if(! (base$id in wmap))
wmap[base$id] = {};
var required = schema["required"] || [];
if(schema["allOf"]){
_.each(schema["allOf"],function(value) {
if(value["$ref"]){
let obj,link;
var refArr = get$refType(value["$ref"]);
if(refArr.refType === "yRelWithDef"){
refArr.startpart = base$id
}
if(smap[refArr.startpart]){
obj=smap[refArr.startpart].jsonSchema;
if(refArr.refType != "yRelWithDef"){
link=normaliseLinks(obj,refArr);
if(!wmap[base$id][refArr.startpart]){
wmap[base$id][refArr.startpart]=link;
}
}
if(pointer.has(obj,refArr.endpart)){
var ischema = _.cloneDeep(pointer.get(obj, refArr.endpart));
if(refArr.refType === "yAbsFSchema"){
processSchema(ischema).then((psSchema) => {
if( psSchema["properties"] ){
_.forOwn(psSchema["properties"],(val,key,object) => {
processFurther(val,key,refArr.startpart).then((pfSchema)=>{
if(pfSchema){
schema.properties[key] = pfSchema;
schema.properties[key].$oSchema={}
schema.properties[key].$oSchema.$linkVal=link.$linkVal
schema.properties[key].$oSchema.$linkPath=link.$linkPath
if(pfSchema["required"]){
if(key in pfSchema["required"]){
schema.required.push(key);
}
}
}
});
})
}
})
}
else{
if( ischema["properties"] ){
_.forOwn(ischema["properties"],(val,key,object) => {
processFurther(val,key,refArr.startpart).then((pfSchema)=>{
if(pfSchema){
schema.properties[key] = pfSchema;
if(refArr.refType === "yAbsWithDef"){
schema.properties[key].$oSchema={}
schema.properties[key].$oSchema.$linkVal=link.$linkVal
schema.properties[key].$oSchema.$linkPath=link.$linkPath
}
if(ischema["required"]){
if(key in ischema["required"])
schema.required.push(key);
}
}
else {
//error
}
});
})
}
}
}
}
}else{
_.forOwn(value,function(val,key){
schema[key]=val;
//
})
// TODO add properties if there // behaviour to be decided
}
});
resolve(schema);
}
else if(schema["properties"]){
_.forOwn(schema["properties"],(val,key,object) => {
processFurther(val,key,base$id).then((pfSchema)=>{
if(pfSchema){
schema.properties[key] = pfSchema;
if(pfSchema["required"]){
if(key in pfSchema["required"]){
schema.required.push(key);
}
}
}
});
})
//TODO check if something missing left here
resolve(schema);
}
})
//generic $ref resolve present in top properties
}
var resolveRef=function(key,obj){
var resolve$ref = Promise.method(function(val,base$id){
let obj,link;
if(! (base$id in wmap) )
wmap[base$id] = {};
let refArr = get$refType(val["$ref"]);
if(refArr.refType === "yRelWithDef"){
refArr.startpart = base$id
}
if(smap[refArr.startpart]){
obj=smap[refArr.startpart].jsonSchema;
if(refArr.refType != "yRelWithDef"){
link = normaliseLinks(obj,refArr);
if(!wmap[base$id][refArr.startpart]){
wmap[base$id][refArr.startpart]=link;
}
}
if(refArr.refType === "yAbsFSchema"){
val.$linkVal = link.$linkVal;
val.$linkPath = link.$linkPath;
return val;
}
if(pointer.has(obj,refArr.endpart)){
var ischema = _.cloneDeep(pointer.get(obj, refArr.endpart));
_.forOwn(val,(v,k)=>{
if(k != "$ref"){
ischema[k]=v;
}
});
return processISchema(ischema,refArr.startpart);
}
}
})
var processISchema = Promise.method(function(schema,base$id){
let refArr;
if(! (base$id in wmap) )
wmap[base$id] = {};
if(schema["anyOf"] || schema["oneOf"]){
// var $definitions=[]
schema["type"] = schema["anyOf"] ? "anyOf" : "oneOf";
let arr = schema["anyOf"]? schema["anyOf"] : schema["oneOf"];
_.each(arr,function(value,index) {
if(value["$ref"]){
resolve$ref(value,base$id).then((piSchema)=>{
delete arr[index];
arr[index]=piSchema;
})
}
else{
processISchema(value,base$id).then((piSchema)=>{
delete arr[index];
arr[index]=piSchema;
})
}
})
// schema["$definitions"] = $definitions;
return schema;
}
if(schema["items"] ){
let val=schema["items"];
if(! schema["type"])
schema["type"] = "array";
if(_.isArray(val)){
//TODO
}else{
if(val["$ref"]){
resolve$ref(val,base$id).then((piSchema)=>{//check // not sending correct id
schema["items"]=piSchema;
})
}
else{
//TODO if such a scenario
}
}
}
// schema.$definitions = $definitions
return schema;
})
var processFurther = Promise.method(function(val,key,$id){
let base$id =$id
if(val["$ref"]){
return resolve$ref(val,base$id)
}
else {
if(val["items"] && val["type"] === "array"){
if(val["items"]["$ref"]){
resolve$ref(val["items"]).then((s)=>{
_.forOwn(s,(v,k)=>{
if(k != "$ref"){
val["items"][k]=v;
}
});
})
}
}
//TODO if any other keyword
return val
}
})
var Schema=function(ajv,schemaMap){
this._ajv = ajv;
this._schemaPathMap=schemaMap;
}
Schema.resolveRef=function(key,obj,currpath){
if(key === "$ref"){
var refVal=obj[key];
var refVal = obj[key];
if( absUrlRegex.test(refVal) ){
obj.$linkPath = refVal;
var temp=refVal.split("/")
obj.$linkVal = temp.pop() || temp.pop();
let parsedUrl = refVal.split("#");
let basepath = parsedUrl[0] ;
if(basepath in this._schemaPathMap){
let newpath = path.relative(path.dirname(currpath),this._schemaPathMap[basepath].filePath).replace(/\\/g, '/'); //to cater windows paths
obj["$ref"] = newpath;
var temp = newpath.slice(0, -5).split("/");
obj.$linkVal = path.basename(newpath).slice(0, -5);
obj.$linkPath = temp.join("/")+".md";
//TODO display with title or file path name title
}
else {
obj.$linkPath = refVal;
var temp = refVal.split("/")
obj.$linkVal = temp.pop() || temp.pop();
}
}
else if(refVal.startsWith(deff)) {
obj.$linkVal=refVal.slice(deff.length);
obj.$linkPath="#"+obj.$linkVal.replace(/ /g,'-');
obj.$linkVal = refVal.slice(deff.length);
obj.$linkPath = "#"+obj.$linkVal.replace(/ /g,'-');
}
else if(refVal.endsWith("json")){
var temp=refVal.slice(0, -5).split("/");
obj.$linkVal=temp[temp.length - 1];
obj.$linkPath=temp.join("/")+".md";
var temp = refVal.slice(0, -5).split("/");
obj.$linkVal = temp[temp.length - 1];
obj.$linkPath = temp.join("/")+".md";
}
}
if(key === "anyOf" || key === "oneOf" || key === "allOf")
obj.$type=key;
return;
}
var traverseSchema = function(object){
var traverseSchema = function(object,schemaFilePath){
return new Promise((resolve,reject) => {
var recurse=function(curr,key,prev){
if(key){
......@@ -72,7 +369,7 @@ var traverseSchema = function(object){
if(Array.isArray(curr))
curr.map((item,index) => recurse(item,index,curr));
else {
(typeof curr === 'object') ? Object.keys(curr).map(key => recurse(curr[key],key,curr)):resolveRef(key,prev);
(typeof curr === 'object') ? Object.keys(curr).map(key => recurse(curr[key],key,curr)):Schema.resolveRef(key,prev,schemaFilePath);
}
return object;
}
......@@ -81,7 +378,7 @@ var traverseSchema = function(object){
}
Schema.getExamples=function(filePath,schema){
Schema.getExamples = function(filePath,schema){
var exampleFileNames=[];
var examples=[];
var dirname=path.dirname(filePath);
......@@ -111,8 +408,7 @@ Schema.getExamples=function(filePath,schema){
})
}
function getDescription(filePath,schema){
Schema.getDescription = function(filePath,schema){
var temp=path.basename(filePath,path.extname(filePath));
//TODO should err be thrown here?
......@@ -128,25 +424,49 @@ function getDescription(filePath,schema){
}
Schema.setAjv=function(ajv){
this._ajv=ajv;
}
Schema.load = function(schemaFilePath, baseURL){
Schema.setSchemaPathMap=function(schemaMap){
this._schemaPathMap=schemaMap;
}
return fs.readFileAsync(schemaFilePath)
.then((schema)=>Schema.getExamples(schemaFilePath,JSON.parse(schema)))
.then((egs_schema) => getDescription(schemaFilePath,egs_schema))
.then((all_schema) => {
var schemaClone = Object.assign({}, all_schema);
return Promise.props({
wSchema:schemaClone,
mSchema:traverseSchema(all_schema)
Schema.load = function(schemaMap,schemaPath,outDir,metaElements){
smap=schemaMap;
let keys = Object.keys(schemaMap);
return Promise.mapSeries(keys,(schemaKey) => {
{
var props = Object.keys(wmap);
for (var i = 0; i < props.length; i++) {
delete wmap[props[i]];
}
}
})
let schema = schemaMap[schemaKey].jsonSchema;
sPath=schemaMap[schemaKey].filePath;
return Schema.getExamples(schemaMap[schemaKey].filePath,schema)
.then((egs_schema) => Schema.getDescription(schemaMap[schemaKey].filePath,egs_schema))
.then((all_schema) => {
var schemaClone = _.cloneDeep(all_schema);
// return Promise.props({
// wSchema:schemaClone,
// mSchema:traverseSchema(all_schema,schemaMap[schemaKey].filePath)
// })
return processSchema(schemaClone).then((mSchema)=>{
mSchema.metaElements=metaElements;
return {mSchema:mSchema,wSchema:all_schema,dep:wmap}
})
}).then((object)=>{
return Promise.all([Writer.generateMarkdown(schemaMap[schemaKey].filePath,object.mSchema,schemaPath,outDir,object.dep),
Writer.generateNewSchemaFiles(schemaMap[schemaKey].filePath,object.wSchema,schemaPath,outDir)]);
})
// })
}).then(()=>{
// console.log(JSON.stringify(wmap));
})
.catch((err) => console.error(err))
.catch((err) => console.error(err));
}
......
var Promise=require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var _ = require('lodash');
var async = require('async');
var ejs = require('ejs');
var logger = require('winston');
var mkdirp = Promise.promisify(require('mkdirp'));
var readdirp = require('readdirp');
var validUrl = require("valid-url");
var url = require("url");
// var Writer = function(schemaPath,outDir){
// this._outDir = outDir;
// this._schemaPath = schemaPath;
// };
var Writer = {}
var writeFile = function(outputDir, fileName, data) {
if(!fs.existsSync(outputDir)){
return mkdirp(outputDir).then((err)=>{
return fs.writeFileAsync(path.join(outputDir, fileName), data);
})
}
else {
return fs.writeFileAsync(path.join(outputDir, fileName), data);
}
}
Writer.generateMarkdown = function(filename, schema,schemaPath,outDir,dependencyMap) {
var ctx = {
schema: schema,
_: _,
validUrl: validUrl,
dependencyMap:dependencyMap
};
ejs.renderFile(path.join(__dirname,'../templates/md/topSchema.ejs'), ctx , { debug: false },function(err,str){
if(err)
console.error(err);
return writeFile(path.join(path.join(outDir), path.dirname(filename.substr(schemaPath.length))), path.basename(filename).slice(0, -5)+ '.md', str);
})
}
Writer.generateNewSchemaFiles = function(filename, schema,schemaPath,outDir) {
return writeFile(path.join(path.join(outDir,"_newSchema"), path.dirname(filename.substr(schemaPath.length))), path.basename(filename), JSON.stringify(schema, null, 4));
}
module.exports = Writer;
......@@ -8,21 +8,12 @@ function displayStringIfExists(object,key,str){
if(object[key])
return str;
}
%><%- HelperFunctions.displayType(nschema) %><%- displayIfExists(nschema,"description") %><%- HelperFunctions.getSimpleKeywords(nschema) %><%- displayStringIfExists(nschema,"properties"," \n**Properties**") %><% if(nschema.properties){ var resetVal=HelperFunctions.nestLevel;
Object.keys(nschema.properties).map((prop) => { var value= nschema.properties[prop]; HelperFunctions.nestLevel= resetVal+1;%><%- " \n"+Array(HelperFunctions.nestLevel * 4).join(" ") %><% if(value["title"]) {%><%- "* **"+value["title"]+"**" %><%} else{ %><%- "* **"+HelperFunctions.linkProperty(prop)+"**" %><% } %><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:true,nchild:0}) %><% }); } %><%
Object.keys(nschema).map((keyword) => {
var value=nschema[keyword];
switch(keyword){
case "oneOf":
case "allOf":
case "anyOf":
case "items":{ %><%- HelperFunctions.getDescriptionForKeyword(keyword,value) %><%
if(_.isArray(value)){
value.map((item,index)=>{%><%- include('innerSchema', {nschema: item, HelperFunctions:HelperFunctions,flag:false,nchild : Object.keys(value).length}) %><% });
}
else if(typeof value === "object"){%><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:false,nchild : Object.keys(value).length}) %><% }
} break;
default: return;
}
})
%><%- HelperFunctions.checkRefrence(nschema,flag,nchild) %>
%><%- HelperFunctions.displayType(nschema,1) %><%- HelperFunctions.displayFormat(nschema)%>
<% if(nschema["$oSchema"]) { %>* **Defined In:** <%- HelperFunctions.createLink(nschema.$oSchema.$linkVal,nschema.$oSchema.$linkPath) %>
<% }%><%- displayIfExists(nschema,"description") %><%- HelperFunctions.getSimpleKeywords(nschema) %><%- displayStringIfExists(nschema,"properties"," \n**"+ sName.charAt(0).toUpperCase() + sName.slice(1) + " Properties**") %><%
if(nschema.properties){ var resetVal=HelperFunctions.nestLevel;
Object.keys(nschema.properties).map((prop) => { var value= nschema.properties[prop]; HelperFunctions.nestLevel= resetVal+1;%><%- " \n"+Array(HelperFunctions.nestLevel * 4).join(" ") %><% if(value["title"])
{%><%- "* **"+value["title"]+"**" %><%} else{ %><%- "* **"+HelperFunctions.linkProperty(prop)+"**" %><%
} %><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:true,nchild:0})
%><% });
} %>
......@@ -3,7 +3,7 @@
nestLevel:0,
isRequired : function (key,requiredProperties) {
if( _.indexOf(requiredProperties,key,0) != -1 )
return " \n_Required Property_";
return " \n* **Required**";
else
return "";
},
......@@ -21,17 +21,18 @@
},
checkRefrence: function(refObject,flag,nchild){
if(refObject.$linkVal && refObject.$linkPath){
if(flag)
return " \n **Referenced From** "+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
else if(nchild > 0)
return " \n* "+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
else
return " \n"+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
}
// if(refObject.$linkVal && refObject.$linkPath){
// if(flag)
// return " \n **Refrenced From** "+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
// else if(nchild > 0)
// return " \n* "+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
// else
// return " \n"+ HelperFunctions.createLink(refObject.$linkVal,refObject.$linkPath);
// }
},
escapeText: function(text){
return text.replace(/\n\n/g," \n").replace(/\n- /g,"\n - ");
return text.replace(/\n- /g,"\n - ");
},
getDescriptionForKeyword: function(keyword,value){
......@@ -41,8 +42,8 @@
case "anyOf": return " \n**Any one of the following conditions must be met**" ;
case "items": {
if(typeof value === "object" && value.type)
return " \n **Array of**" + value.type;
else return " \n **Array containing**";
return " \n **Array of**" + " " + value.type;
else return " \n **Array Of**";
}
case "contains": return "At least one of the element of array should be following \n" ;
case "patternProperties": return "Pattern Specific Properties \n";
......@@ -71,27 +72,129 @@
});
return str;
},
displayType: function(value){
var typeVal=value["type"];
displayType: function(value,level){
var typeVal=value["type"];
var word1="";
switch(typeVal){
case "oneOf" : word1 = "Only one of "; break;
case "anyOf" : word1 = "Either "; break;
case "array" : word1 = "Array of "; break;
case "object": word1 = "";break;
}
var str2="",str="",str3="";
if(level === 1)
str=" \n* **Type:** "
else if(level === 3)
str=" "
else if(level === 4)
str=" \n * Type: "
else if(level === 2)
str= " \n * "
if(!value["$ref"]){
// var str=" \n "//" Type: ",
if(typeVal === "anyOf" || typeVal === "oneOf"){
var arr= value[typeVal]; //if not throw error
_.each(arr,function(item,index){
if(item["type"] != "anyOf" && item["type"] != "oneOf" && item["type"] != "array"){
if(item["$ref"]){
if(index === 0)
{str2= str2 + HelperFunctions.createLink(item["$linkVal"],item["$linkPath"]);}
else
str2= str2 + " or "+ HelperFunctions.createLink(item["$linkVal"],item["$linkPath"])
}
else{
//TODO
}
}
else{
str2= str2 + HelperFunctions.displayType(item,2);
//return HelperFunctions.displayType(item);
}
var str1=" \n**Type:** ", str2="";
if(value["format"])
str2=str2 + '`'+value["format"]+ '` ';
else if(typeVal){
if(_.isArray(typeVal)){
_.each(typeVal, (item,index) => {
if(index != typeVal.length - 1)
str2=str2 + '`'+item+ '`, '
else str2=str2 + '`'+item+ '`';
})
}
else
str2=str2 + '`'+typeVal+ '`';
else if(typeVal === "array" && value["items"] ){
//str2=str2+"Array Of ";
if(_.isArray(value["items"])){
_.forOwn(value["items"],(item,key,object)=>{
if(item["type"] != "anyOf" && item["type"] != "oneOf" && item["type"] != "array"){
if(item["$ref"]){
// str2= str2 + HelperFunctions.createLink(item["$linkVal"],item["$linkPath"]) + " or "
}
else{
//TODO
}
}
else{
str2= str2 + HelperFunctions.displayType(item,2);
}
})
}
else if(typeof value["items"] === "object"){
if(value["items"]["type"] != "anyOf" && value["items"]["type"] != "oneOf" && value["items"]["type"] != "array"){
if(value["items"]["$ref"] && !value["items"]["properties"]){
str2= str2 + HelperFunctions.createLink(value["items"]["$linkVal"],value["items"]["$linkPath"]);
}
else{
str2=""
if(value["items"]["properties"]){
var nschema=value["items"];
str3=str3+"following Properties ";
_.forOwn(nschema.properties,(val,key) =>
{
str3=str3+"\n * **"+HelperFunctions.linkProperty(key)+"**"+HelperFunctions.displayType(val,4)+displayIfExists(val,"description")
})
}else {
if(value["items"]["type"])
if(value["items"]["type"].length > 1)
str3 = str3 + value["items"]["type"];
}
}
}
else{
str2= str2 + HelperFunctions.displayType(value["items"],3);
}
}
}
else if(typeVal){
if(_.isArray(typeVal)){
_.each(typeVal, (item,index) => {
if(index != typeVal.length - 1)
str2=str2 +item+ ', '
else str2=str2 + item;
})
}
else
str2=str2 + typeVal;
}
if(str2.length > 1)
return str+ word1 + str2 ;
else if(str3.length > 1)
return str+ word1 + str3 ;
else{
return ""
}
}
if(str2.length > 1)
return str1 + str2;
else
return ""
else {
return str + word1 + HelperFunctions.createLink(value["$linkVal"],value["$linkPath"])
}
},
displayFormat: function(value){
var str = "";
if(value["format"])
str = str + " \n* **Format:** " +value["format"] ;
return str;
},
getSimpleKeywords: function (object){
var str="";
......@@ -119,12 +222,69 @@
})
return str;
},
getDependencies: function(dependencyMap,schema){
var id="",title="";
if(schema["$id"])
id=schema["$id"];
if(schema["title"])
title=schema["title"]
var mainId=id;
var str = title + " is based on: \n";
var usemap={};
var str2="";
var recurse = function(dmap,level){
if(dmap)
{
if(Object.keys(dmap).length > 0){
_.forOwn(dmap,(val,key) => {
if(!(key in usemap)){
str2 = str2 + " \n" +Array(level * 4).join(" ") + "* "+HelperFunctions.createLink(val.$linkVal,val.$linkPath);
// console.log("str2");
usemap[key]=1;
if(dependencyMap[key] && Object.keys(dependencyMap[key]).length > 0){
if(key != mainId)
recurse(dependencyMap[key],level+1)
}
else
return str2;
}
else
return ""
})
}
else {
return ""
}
}
else
return ""
return str2;
}
if(dependencyMap[id]){
if(Object.keys(dependencyMap[id]).length > 0)
return str + recurse(dependencyMap[id],0)
else
return "";
}
else {
return "";
}
}
}
function displayIfExists(object,key){
if(object[key])
return " \n" + HelperFunctions.escapeText(object[key]);
else
return ""
}
function displayStringIfExists(object,key,str){
......@@ -132,35 +292,29 @@ function displayStringIfExists(object,key,str){
return " \n" + str;
}
%>
%>
<%- displayStringIfExists(schema,"title","# "+schema["title"]) %>
<%- HelperFunctions.displayType(schema) %>
<%- HelperFunctions.getDependencies(dependencyMap,schema) %>
<%- HelperFunctions.displayType(schema,1) %>
<%- displayIfExists(schema,"description") %>
<% Object.keys(schema).map((keyword) => {
var value=schema[keyword];
switch(keyword){
case "oneOf":
case "allOf":
case "anyOf":
case "items":{
%><%- HelperFunctions.getDescriptionForKeyword(keyword,value) %><%if(_.isArray(value)){
value.map((item,index)=>{%><%- include('innerSchema', {nschema: item, HelperFunctions:HelperFunctions,flag:false,nchild : value.length}) %><% });
}else if(typeof value === "object"){
%><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:false,nchild : Object.keys(value).length}) %><% }
} break;
default: return;
}
})
%><%- HelperFunctions.getSimpleKeywords(schema) %>
<% if(schema.properties){ %>
<%- HelperFunctions.getSimpleKeywords(schema) %>
<% if(schema.properties && Object.keys(schema.properties).length > 0){ %>
## Properties
<% Object.keys(schema.properties).map((prop) => { var value= schema.properties[prop]; HelperFunctions.nestLevel = -1; %>
### <%- HelperFunctions.linkProperty(prop) %><%- HelperFunctions.isRequired(prop,schema.required) %><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:true,nchild:0}) %><% });} %>
<% if(schema.definitions){ %>
<% Object.keys(schema.properties).map((prop) => { var value= schema.properties[prop]; HelperFunctions.nestLevel = 0; %>
### <%- HelperFunctions.linkProperty(prop) %><%- HelperFunctions.isRequired(prop,schema.required) %><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:true,nchild:0,sName:HelperFunctions.linkProperty(prop)}) %><% });} %>
<% if(!schema.properties || (Object.keys(schema.properties).length == 0) && schema.definitions){ %>
## Definitions
<% Object.keys(schema.definitions).map((def) => { var value= schema.definitions[def]; HelperFunctions.nestLevel = 0; %>
### <%- def %><%- include('innerSchema', {nschema: value, HelperFunctions:HelperFunctions,flag:true,nchild:0}) %><% });} %>
\ No newline at end of file
<% Object.keys(schema.definitions).map((def) => { var value= schema.definitions[def]; HelperFunctions.nestLevel = -1; %>
## <%- HelperFunctions.linkProperty(def)
%><% if(value["properties"]){
%>
### Properties
<% Object.keys(value.properties).map((prop) => { var val= value.properties[prop]; HelperFunctions.nestLevel = 0; %>
### <%- HelperFunctions.linkProperty(prop) %><%- HelperFunctions.isRequired(prop,value.required)
%><%- include('innerSchema', {nschema: val, HelperFunctions:HelperFunctions,flag:true,nchild:0,sName:HelperFunctions.linkProperty(prop)
})%><% })
}
})} %>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment