const parseArgs = require('minimist'); const fs = require('fs'); const assert = require('assert'); const util = require('util'); const { resolve } = require('path'); const IDENT = ' '; class MyDoc { constructor() { this.workDir = './'; } async init() { await this.convert(); } async convert() { this.env = fs.readFileSync(`${this.workDir}env.json`, 'utf8'); this.data = ` { if (item.name.slice(-3) == '.js' && item.name != 'common.js') { const c = require(resolve('./') + '/' + item.name.slice(0, -3)); this.convertClass(new c()); } }); this.data += `\n}`; console.log(this.data); } convertClass(c) { c.apis.forEach( (item) => { const method = item.method ? 'GET' : item.method; this.data += ` /** * @api {${method}} ${item.url} * @apiPermission * @apiGroup ${item.group} * @apiVersion 1.0 * @apiDescription ${item.desc} `; if (item.is_json_params) { this.data += ` * @apiParamExample {json} 请求样例:\n`; this.data += ` * {\n`; this.asJsonOut(item.params, 1); this.data += ` * }\n`; } else { this.asParamOut(item.params); } this.data += ` */ `; } ); } getFieldType(val) { if (typeof val == 'string') { return 'String'; } else if (typeof val == 'number') { return 'Number'; } return 'String'; } asParamOut(itemList) { itemList.forEach( (item) => { if (util.isArray(item)) { const paramType = this.getFieldType(item[1]); this.data += ` * @apiParam ${paramType} ${item[0]} ${item[2]}\n`; } else { this.asParamOut(item.fields); } } ); } getJsonValue(val) { if (typeof val == 'number') { return 0; } else { return '""'; } } asJsonOut(itemList, ident) { itemList.forEach( (item) => { const curIdent = (new Array(ident * 4)).fill(' ').join(''); if (util.isArray(item[1])) { if (item[0].slice(0,1) == '!') { const realFieldName = item[0].slice(1); this.data += ` * ${curIdent}'${realFieldName}': [ // struct ${item[2]}\n`; if (item[1].length == 1) { if (util.isArray(item[1][0])) { this.data += ` * ${curIdent + IDENT}'${realFieldName}': [ // struct ${item[2]}\n`; } else { this.data += ` * ${curIdent + IDENT}${this.getJsonValue(item[1])}\n`; } } else { } this.data += ` * ${curIdent}]\n`; } else { this.data += ` * ${curIdent}'${item[0]}': { // struct ${item[2]}\n`; } } else { if (util.isArray(item)) { if (['string', 'number'].indexOf(typeof item[1]) >= 0) { const paramType = this.getFieldType(item[1]); this.data += ` * ${curIdent}'${item[0]}': ${this.getJsonValue(item[1])}, //${item[2]}\n`; } else { this.data += ` * ${curIdent}'${item[0]}': { // struct ${item[1].constructor.name} ${item[2]}\n`; this.asJsonOut(item[1].fields, ident + 1); this.data += ` * ${curIdent}}\n`; } } else if (typeof item == 'object'){ this.asJsonOut(item.fields, ident); } } } ); } } (new MyDoc).init();