diff --git a/cli.js b/cli.js index 5ca576ddfb8e0ffad5fb4cabaf3093554d98859d..bafbbf729a9a5d65ddbe468390f2d3858f4ae887 100644 --- a/cli.js +++ b/cli.js @@ -20,29 +20,29 @@ var readSchemaFile = require('./lib/readSchemaFile'); // parse/process command line arguments var argv = require('optimist') -.usage('Generate Markdown documentation from JSON Schema.\n\nUsage: $0') -.demand('d') -.alias('d', 'input') -// TODO: is baseURL still a valid parameter? -.describe('d', 'path to directory containing all JSON Schemas or a single JSON Schema file. This will be considered as the baseURL. Note that only files ending in .schema.json will be processed.') -.alias('o', 'out') -.describe('o', 'path to output directory') -.default('o', path.resolve(path.join('.', 'out'))) -.alias('m', 'meta') -.describe('m','add metadata elements to .md files Eg -m template=reference. Multiple values can be added by repeating the flag Eg: -m template=reference -m hide-nav=true') -.alias('s','metaSchema') -.describe('s', 'Custom meta schema path to validate schemas') -.alias('x', 'schema-out') -.describe('x', 'output JSON Schema files including description and validated examples in the _new folder at output directory') -.check(function (args) { - if (!fs.existsSync(args.input)) { - throw 'Input file "' + args.input + '" does not exist!'; - } - if (args.s && !fs.existsSync(args.s)) { - throw 'Meta schema file "' + args.s + '" does not exist!'; - } -}) -.argv; + .usage('Generate Markdown documentation from JSON Schema.\n\nUsage: $0') + .demand('d') + .alias('d', 'input') + // TODO: is baseURL still a valid parameter? + .describe('d', 'path to directory containing all JSON Schemas or a single JSON Schema file. This will be considered as the baseURL. Note that only files ending in .schema.json will be processed.') + .alias('o', 'out') + .describe('o', 'path to output directory') + .default('o', path.resolve(path.join('.', 'out'))) + .alias('m', 'meta') + .describe('m','add metadata elements to .md files Eg -m template=reference. Multiple values can be added by repeating the flag Eg: -m template=reference -m hide-nav=true') + .alias('s','metaSchema') + .describe('s', 'Custom meta schema path to validate schemas') + .alias('x', 'schema-out') + .describe('x', 'output JSON Schema files including description and validated examples in the _new folder at output directory') + .check(function (args) { + if (!fs.existsSync(args.input)) { + throw 'Input file "' + args.input + '" does not exist!'; + } + if (args.s && !fs.existsSync(args.s)) { + throw 'Meta schema file "' + args.s + '" does not exist!'; + } + }) + .argv; var ajv = new Ajv({ allErrors: true , messages:true }); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); @@ -52,12 +52,12 @@ var schemaPath = path.resolve(argv.d); var outDir = path.resolve(argv.o); var target = fs.statSync(schemaPath); -if(argv.s){ +if (argv.s){ ajv.addMetaSchema(require(path.resolve(argv.s))); } if (argv.m) { - if(_.isArray(argv.m)){ + if (_.isArray(argv.m)){ _.each(argv.m,function(item){ var meta=item.split('='); if (meta.length === 2) { @@ -77,17 +77,38 @@ if (target.isDirectory()) { // the ajv json validator will be passed into the main module to help with processing var files=[]; readdirp({ root: schemaPath, fileFilter: '*.schema.json' }) - .on('data',(entry) => { - files.push(entry.fullPath); - ajv.addSchema(require(entry.fullPath), entry.fullPath); - }) - .on('end',() => { - Schema.setAjv(ajv); - Schema.setSchemaPathMap(schemaPathMap); - return Promise.reduce(files, readSchemaFile, schemaPathMap) - .then((schemaMap)=>{ - logger.info('finished reading all *.schema.json files in %s, beginning processing....', schemaPath); - return Schema.load(schemaMap, schemaPath, outDir, metaElements); + .on('data',(entry) => { + files.push(entry.fullPath); + ajv.addSchema(require(entry.fullPath), entry.fullPath); + }) + .on('end',() => { + Schema.setAjv(ajv); + Schema.setSchemaPathMap(schemaPathMap); + return Promise.reduce(files, readSchemaFile, schemaPathMap) + .then((schemaMap)=>{ + logger.info('finished reading all *.schema.json files in %s, beginning processing....', schemaPath); + return Schema.load(schemaMap, schemaPath, outDir, metaElements); + }) + .then(() => { + logger.info('Processing complete.'); + }) + .catch((err) => { + logger.error(err); + process.exit(1); + }); + }) + .on('error',(err)=>{ + logger.error(err); + process.exit(1); + }); +} else { + readSchemaFile(schemaPathMap, schemaPath) + .then((schemaMap) => { + ajv.addSchema(require(schemaPath), schemaPath); + Schema.setAjv(ajv); + Schema.setSchemaPathMap(schemaPathMap); + logger.info('finished reading %s, beginning processing....', schemaPath); + return Schema.load(schemaMap , schemaPath, outDir, metaElements); }) .then(() => { logger.info('Processing complete.'); @@ -96,25 +117,4 @@ if (target.isDirectory()) { logger.error(err); process.exit(1); }); - }) - .on('error',(err)=>{ - logger.error(err); - process.exit(1); - }); -} else { - readSchemaFile(schemaPathMap, schemaPath) - .then((schemaMap) => { - ajv.addSchema(require(schemaPath), schemaPath); - Schema.setAjv(ajv); - Schema.setSchemaPathMap(schemaPathMap); - logger.info('finished reading %s, beginning processing....', schemaPath); - return Schema.load(schemaMap , schemaPath, outDir, metaElements); - }) - .then(() => { - logger.info('Processing complete.'); - }) - .catch((err) => { - logger.error(err); - process.exit(1); - }); } diff --git a/lib/readSchemaFile.js b/lib/readSchemaFile.js index 5ef273b8b60ce637e5ce1061502398d1019c9f3f..9ab47ad5efecb30f75430c55b1ebeb07048a6ba9 100644 --- a/lib/readSchemaFile.js +++ b/lib/readSchemaFile.js @@ -12,23 +12,23 @@ var fs = Promise.promisifyAll(require('fs')); // Returns the schema path map object. module.exports = function readSchemaFile(schemaPathMap, fullPath) { if (!schemaPathMap) { - schemaPathMap = {}; + schemaPathMap = {}; } 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; - } + .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; - } - return schemaPathMap; - }); + } else { + schemaPathMap[fullPath] = obj; + } + return schemaPathMap; + }); }; diff --git a/lib/schema.js b/lib/schema.js index 5448c2d2d6644bb452fdb700e91719d7d2664090..10d34e303af2c7375570990ca9288ccc9b1bcca2 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -6,13 +6,13 @@ */ 'use strict'; -var validUrl = require("valid-url"); +var validUrl = require('valid-url'); var util = require('util'); var path = require('path'); var _ = require('lodash'); var logger = require('winston'); var readdirp = require('readdirp'); -var url = require("url"); +var url = require('url'); var Promise=require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var Writer=require('./writeFiles'); @@ -24,96 +24,88 @@ 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 startpart = '', endpart = '', refType = ''; + var arr = refValue.split('#'); + if (arr.length > 1) {endpart=arr[1];} - startpart=arr[0] + startpart=arr[0]; //TODO yRelNoDef //relative-- yRelWithDef, yRelNoDef, //absolute-- yAbsWithDef, yAbsFSchema, yAbsWithFragment - var refType="",currStartId; + 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" + 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" + } else { + if (endpart.startsWith(deff)){ + refType = 'yRelWithDef'; } } // } - return {startpart,endpart,refType} + return { startpart,endpart,refType }; } function normaliseLinks(obj,refArr){ let basepath = refArr.startpart ; - let $linkVal = "", $linkPath = ""; - if(basepath in smap){ + 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"; + 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"]; + 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"]){ + 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 + var refArr = get$refType(value['$ref']); + if (refArr.refType === 'yRelWithDef'){ + refArr.startpart = base$id; } - if(smap[refArr.startpart]){ + if (smap[refArr.startpart]){ obj=smap[refArr.startpart].jsonSchema; - if(refArr.refType != "yRelWithDef"){ + if (refArr.refType != 'yRelWithDef'){ link=normaliseLinks(obj,refArr); - if(!wmap[base$id][refArr.startpart]){ + if (!wmap[base$id][refArr.startpart]){ wmap[base$id][refArr.startpart]=link; } } - if(pointer.has(obj,refArr.endpart)){ + if (pointer.has(obj,refArr.endpart)){ var ischema = _.cloneDeep(pointer.get(obj, refArr.endpart)); - if(refArr.refType === "yAbsFSchema"){ + if (refArr.refType === 'yAbsFSchema'){ processSchema(ischema).then((psSchema) => { - if( psSchema["properties"] ){ - _.forOwn(psSchema["properties"],(val,key,object) => { + if ( psSchema['properties'] ){ + _.forOwn(psSchema['properties'],(val,key,object) => { processFurther(val,key,refArr.startpart).then((pfSchema)=>{ - if(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 + 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"]){ + if (pfSchema['required']){ + if (key in pfSchema['required']){ schema.required.push(key); } } @@ -121,34 +113,31 @@ function processSchema(schema){ }); - }) + }); } - }) + }); - } - else{ - if( ischema["properties"] ){ - _.forOwn(ischema["properties"],(val,key,object) => { + } else { + if ( ischema['properties'] ){ + _.forOwn(ischema['properties'],(val,key,object) => { processFurther(val,key,refArr.startpart).then((pfSchema)=>{ - if(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 (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); + if (ischema['required']){ + if (key in ischema['required']) {schema.required.push(key);} } - } - else { + } else { //error } }); - }) + }); } } @@ -156,39 +145,38 @@ function processSchema(schema){ } - }else{ + } 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) => { + } else if (schema['properties']){ + _.forOwn(schema['properties'],(val,key,object) => { processFurther(val,key,base$id).then((pfSchema)=>{ - if(pfSchema){ + if (pfSchema){ schema.properties[key] = pfSchema; - if(pfSchema["required"]){ - if(key in pfSchema["required"]){ + if (pfSchema['required']){ + if (key in pfSchema['required']){ schema.required.push(key); } } } }); - }) + }); //TODO check if something missing left here resolve(schema); } - }) + }); @@ -198,228 +186,209 @@ function processSchema(schema){ 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; + 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(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); + } + 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"]){ + 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"]; + schema['type'] = schema['anyOf'] ? 'anyOf' : 'oneOf'; + let arr = schema['anyOf']? schema['anyOf'] : schema['oneOf']; _.each(arr,function(value,index) { - if(value["$ref"]){ + if (value['$ref']){ resolve$ref(value,base$id).then((piSchema)=>{ delete arr[index]; arr[index]=piSchema; - }) - } - else{ + }); + } else { processISchema(value,base$id).then((piSchema)=>{ delete arr[index]; arr[index]=piSchema; - }) + }); } - }) + }); // schema["$definitions"] = $definitions; return schema; } - if(schema["items"] ){ + if (schema['items'] ){ - let val=schema["items"]; - if(! schema["type"]) - schema["type"] = "array"; - if(_.isArray(val)){ + let val=schema['items']; + if (!schema['type']) {schema['type'] = 'array';} + if (_.isArray(val)){ //TODO - }else{ - if(val["$ref"]){ + } else { + if (val['$ref']){ resolve$ref(val,base$id).then((piSchema)=>{//check // not sending correct id - schema["items"]=piSchema; - }) - } - else{ + 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; - } + 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 + return val; } -}) +}); var Schema=function(ajv,schemaMap){ this._ajv = ajv; this._schemaPathMap=schemaMap; -} +}; Schema.resolveRef=function(key,obj,currpath){ - if(key === "$ref"){ + if (key === '$ref'){ var refVal = obj[key]; - if( absUrlRegex.test(refVal) ){ - let parsedUrl = refVal.split("#"); + if ( absUrlRegex.test(refVal) ){ + let parsedUrl = refVal.split('#'); let basepath = parsedUrl[0] ; - if(basepath in this._schemaPathMap){ + 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['$ref'] = newpath; + var temp = newpath.slice(0, -5).split('/'); obj.$linkVal = path.basename(newpath).slice(0, -5); - obj.$linkPath = temp.join("/")+".md"; + obj.$linkPath = temp.join('/')+'.md'; //TODO display with title or file path name title - } - - else { + } else { obj.$linkPath = refVal; - var temp = refVal.split("/") + var temp = refVal.split('/'); obj.$linkVal = temp.pop() || temp.pop(); } - } - else if(refVal.startsWith(deff)) { + } else if (refVal.startsWith(deff)) { 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.$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"; + obj.$linkPath = temp.join('/')+'.md'; } } - if(key === "anyOf" || key === "oneOf" || key === "allOf") - obj.$type=key; + if (key === 'anyOf' || key === 'oneOf' || key === 'allOf') {obj.$type=key;} return; -} +}; var traverseSchema = function(object,schemaFilePath){ return new Promise((resolve,reject) => { var recurse=function(curr,key,prev){ - if(key){ - if(key === "anyOf" || key === "oneOf" || key === "allOf") - prev.$type=key; + if (key){ + if (key === 'anyOf' || key === 'oneOf' || key === 'allOf') {prev.$type=key;} } var result; - if(Array.isArray(curr)) - curr.map((item,index) => recurse(item,index,curr)); - else { + 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)):Schema.resolveRef(key,prev,schemaFilePath); } return object; - } + }; resolve(recurse(object)); }); -} +}; Schema.getExamples = function(filePath,schema){ var exampleFileNames=[]; var examples=[]; var dirname=path.dirname(filePath); var filename=path.basename(filePath,path.extname(filePath)); - filename=filename.split(".")[0]+".example.*.json"; + filename=filename.split('.')[0]+'.example.*.json'; return new Promise((resolve,reject) => { readdirp({ root: dirname, fileFilter: filename }) - .on('data',(entry)=>exampleFileNames.push(entry.fullPath)) - .on('end',() => resolve(exampleFileNames)) - .on('error',() => reject(err)) + .on('data',(entry)=>exampleFileNames.push(entry.fullPath)) + .on('end',() => resolve(exampleFileNames)) + .on('error',() => reject(err)); }).then((exampleFileNames)=>{ - if(exampleFileNames.length > 0){ + if (exampleFileNames.length > 0){ var validate=this._ajv.compile(schema); return Promise.map(exampleFileNames,(entry)=>{ return fs.readFileAsync(entry).then((example)=>{ var data = JSON.parse(example.toString()); var valid = validate(data); - if(valid) - examples.push(data); - else - logger.error(entry+" is an invalid Example"); - }) - }).then(() => {schema.examples=examples; return schema; } ) - } - else - return schema; - }) -} + if (valid) {examples.push(data);} else {logger.error(entry+' is an invalid Example');} + }); + }).then(() => {schema.examples=examples; return schema; } ); + } else {return schema;} + }); +}; Schema.getDescription = function(filePath,schema){ var temp=path.basename(filePath,path.extname(filePath)); //TODO should err be thrown here? - temp=temp.split(".")[0]+".description.md"; + temp=temp.split('.')[0]+'.description.md'; return fs.readFileAsync(path.resolve(path.dirname(filePath),temp),'utf8') - .then((description) => { - schema.description=description; - return schema; - }) - .catch((err) => { - return schema; - }); + .then((description) => { + schema.description=description; + return schema; + }) + .catch((err) => { + return schema; + }); -} +}; Schema.setAjv=function(ajv){ this._ajv=ajv; -} +}; Schema.setSchemaPathMap=function(schemaMap){ this._schemaPathMap=schemaMap; -} +}; Schema.load = function(schemaMap,schemaPath,outDir,metaElements){ smap=schemaMap; @@ -435,29 +404,29 @@ Schema.load = function(schemaMap,schemaPath,outDir,metaElements){ 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((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)); // }) -} +}; module.exports = Schema; diff --git a/lib/writeFiles.js b/lib/writeFiles.js index 2676798855f565ee0afb79c6f7d140941d10f539..870870741e526afac969990596b647ad562f918b 100644 --- a/lib/writeFiles.js +++ b/lib/writeFiles.js @@ -14,27 +14,26 @@ 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 validUrl = require('valid-url'); +var url = require('url'); // var Writer = function(schemaPath,outDir){ // this._outDir = outDir; // this._schemaPath = schemaPath; // }; -var Writer = {} +var Writer = {}; var writeFile = function(outputDir, fileName, data) { - if(!fs.existsSync(outputDir)){ + if (!fs.existsSync(outputDir)){ return mkdirp(outputDir).then((err)=>{ return fs.writeFileAsync(path.join(outputDir, fileName), data); - }) - } - else { + }); + } else { return fs.writeFileAsync(path.join(outputDir, fileName), data); } -} +}; Writer.generateMarkdown = function(filename, schema,schemaPath,outDir,dependencyMap) { - + var ctx = { schema: schema, _: _, @@ -43,15 +42,14 @@ Writer.generateMarkdown = function(filename, schema,schemaPath,outDir,dependency }; ejs.renderFile(path.join(__dirname,'../templates/md/topSchema.ejs'), ctx , { debug: false },function(err,str){ - if(err) - console.error(err); + 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)); + 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; diff --git a/spec/lib/readSchemaFile.spec.js b/spec/lib/readSchemaFile.spec.js index 873959dca5fe64ae609250b7d14ebf234e5a055c..95140a9fc462366227aac884880936c2edb2e6d7 100644 --- a/spec/lib/readSchemaFile.spec.js +++ b/spec/lib/readSchemaFile.spec.js @@ -17,13 +17,13 @@ describe('readSchemaFile module', () => { describe('reading schema files without an $id key', () => { it('should return a schema path map with path to the file as a key, and object value with path and json schema', (done) => { readSchemaFile({}, fakePath) - .then((map) => { - expect(map[fakePath]).toBeDefined(); - expect(map[fakePath].filePath).toEqual(fakePath); - expect(map[fakePath].jsonSchema).toEqual({schema:'yes'}); - }) - .catch(fail) - .done(done); + .then((map) => { + expect(map[fakePath]).toBeDefined(); + expect(map[fakePath].filePath).toEqual(fakePath); + expect(map[fakePath].jsonSchema).toEqual({ schema:'yes' }); + }) + .catch(fail) + .done(done); }); }); describe('reading schema files with an $id key', () => { @@ -32,23 +32,23 @@ describe('readSchemaFile module', () => { }); it('should return a schema path map with $id value as a key, and object value with path and json schema', (done) => { readSchemaFile({}, fakePath) - .then((map) => { - expect(map['allyourbase']).toBeDefined(); - expect(map['allyourbase'].filePath).toEqual(fakePath); - expect(map['allyourbase'].jsonSchema).toEqual({$id:'allyourbase'}); - }) - .catch(fail) - .done(done); + .then((map) => { + expect(map['allyourbase']).toBeDefined(); + expect(map['allyourbase'].filePath).toEqual(fakePath); + expect(map['allyourbase'].jsonSchema).toEqual({ $id:'allyourbase' }); + }) + .catch(fail) + .done(done); }); it('should not overwrite the value for an existing $id key in the schema path map', (done) => { - readSchemaFile({allyourbase:{}}, fakePath) - .then((map) => { - expect(map['allyourbase']).toBeDefined(); - expect(map['allyourbase'].filePath).not.toBeDefined(); - expect(map['allyourbase'].jsonSchema).not.toBeDefined(); - }) - .catch(fail) - .done(done); + readSchemaFile({ allyourbase:{} }, fakePath) + .then((map) => { + expect(map['allyourbase']).toBeDefined(); + expect(map['allyourbase'].filePath).not.toBeDefined(); + expect(map['allyourbase'].jsonSchema).not.toBeDefined(); + }) + .catch(fail) + .done(done); }); }); });