公司在之前進行存管對接后悄蕾,對內(nèi)部架構(gòu)進行了細(xì)分,業(yè)務(wù)邏輯也比之前復(fù)雜了不少奠骄,由此數(shù)據(jù)庫文檔的必要性顯得十分重要含鳞;組長參照了mysql在定義字段時添加的comment字段生成文檔蝉绷,在mongoose也使用了這一方式熔吗,然后通過讀取model.js生成符合apidoc的注釋,通過apidoc生成文檔宵晚。
-
先看效果:
Screenshot from 2017-09-17 23-43-58.png
說來慚愧,這任務(wù)本來是落在我身上吱型,當(dāng)時我根據(jù)apidoc的樣式模擬寫出html津滞,但是顯示效果不好铝侵,組長就想到利用apidoc來生成文檔,但是我拖拉了兩個周末后組長自己寫了demo咪鲜,而后我只是做了樣式優(yōu)化的部分
// 這是之前我寫得第一版
const TYPES = [String, Date, Boolean, Number]
const field = User.schema.obj
// console.log(field.type.name, field.comment)
let tbody = ''
// 定義空格符
const space = ' '
function renderTbody(data, index) {
for (const attr in data) {
index = index || 0
// 如果是子屬性,則添加空格符
let gap = ''
for (let i = 0; i < index; i++) {
gap += space
}
if (_.includes(TYPES, field[attr])) {
tbody += `
<tr>
<td class="code">${gap}${attr}</td>
<td>${typeof field[attr]()}</td>
<td><p>${attr}</p></td>
</tr>
`
} else if (attr.comment) {
tbody += `
<tr>
<td class="code">${gap}${attr}</td>
<td>${typeof field[attr].type()}</td>
<td><p>${field[attr].comment}</p></td>
</tr>
`
} else {
renderTbody(field[attr], index + 1)
}
}
}
renderTbody(field)
const body = `
<table class="table">
<thead>
<tr>
<th style="width: 30%">Field</th>
<th style="width: 10%">Type</th>
<th style="width: 40%">Description</th>
</tr>
</thead>
<tbody>
${tbody}
</tbody>
</table>
`
let html = `<!DOCTYPE html>
<html>
<head id="head">
<meta charset="UTF-8">
<meta name="format-detection" content="telephone=no">
<meta name="Description" content="modelDoc">
<title>modelDoc</title>
<link rel="stylesheet" type="text/css" href="./modelDoc.css">
</head>
<body>
<h3>${User.schema.name}</h3>
${body}
</body>
</html>`
console.log('生成頁面...')
fs.writeFileSync(path.resolve(__dirname, '../../assets/modelDoc/index.html'), html)
process.exit(0)
以下是apidoc的版本
- 先來看看model的定義
attributes: {
uid: { type: String, required: true, index: true, comment: '用戶id' },
amount: { type: Number, required: true, comment: '金額' },
oType: {
type: Number,
required: true,
enum: Object.values(Constant.ORDER_TYPE),
comment: '訂單類型'
},
channel: { type: String, required: true, default: Constant.CHANNEL.SYSTEM, comment: '訂單來源渠道' },
os: { type: String, required: true, default: Constant.CLIENT.SYSTEM, comment: '發(fā)起終端' },
status: { type: Number, required: true, comment: '狀態(tài)' },
time: { type: Number, required: true, comment: '訂單創(chuàng)建時間' },
doneTime: { type: Number, comment: '訂單完成時間' },
expireTime: { type: Number, comment: '訂單失效時間' },
// 充值提現(xiàn)訂單有
bank: { type: String, comment: '銀行編碼' },
bankcard: { type: String, comment: '銀行卡號' },
// 購買還款訂單有
product: { type: Object, comment: '產(chǎn)品' },
asset_id: { type: String, comment: '資產(chǎn)id' },
extend: {
type: Object
// 統(tǒng)計所有用到extend的地方疟丙,都加上
// isLazy: {type: Boolean, comment: '是否自動投資'}
},
message: { type: String, comment: '失敗原因' }
}
- model層使用了腳本讀取文件
const fs = require('fs');
const path = require('path');
const models = fs.readdirSync(path.resolve(__dirname, './'));
let ret = {};
for (const model of models) {
ret[model.slice(0, model.indexOf('.js'))] = require(`./${model}`)
}
module.exports = ret;
因此在讀取model時只需要const models = require('../../app/model/')
- 先定義apidoc的name和group,然后通過generateFieldDoc函數(shù)生成相應(yīng)的注釋享郊,最后將生成的注釋寫入指定的文件內(nèi)
for (let i in models) {
let model = models[i]
const schema = model.schema.obj
doc += `
/**
* @api {POST} /${model.modelName} ${model.modelName}
* @apiName ${model.modelName}
* @apiGroup model
`
for (let attr in schema) {
doc += generateFieldDoc(attr, schema[attr])
}
doc += ' */\n'
}
fs.writeFileSync(path.resolve(__dirname, '../../app/model/modelDoc.js'), doc)
process.exit(0)
function generateFieldDoc (key, value) {
let prefix = ' * @apiParam'
let defaultStr = ''
let enumStr = ''
// 這里調(diào)用lodash的isFunction览祖,兼容type: String這種寫法
if (_.isFunction(value)) {
return `${prefix} {${value.name}} ${key}\n`
}
if (_.isObject(value) && value.type) {
let description = value.comment || ''
// apidoc沒有索引標(biāo)志,所以只能寫在description
if (value.index) {
description += ' (加索引)'
}
// 只能規(guī)定的值
if (value.enum) {
// 區(qū)分number和string
if (value.type === Number){
enumStr += `=${value.enum.join(',')}`
} else if (value.type === String){
enumStr += `="${value.enum.join('\",\"')}"`
}
}
// 是否有默認(rèn)值
if (value.default) {
defaultStr += value.type === String ? `="${value.default}"` : `=${value.default}`
}
// 是否必填
if (!value.required) {
if (value.enum) {
key = `[${key}`
enumStr = `${enumStr}]`
} else {
key = `[${key}]`
}
}
return `${prefix} {${value.type.name}${enumStr}} ${key}${defaultStr} ${description}\n`
}
const type = _.isArray(value) ? 'Array' : 'Object'
let ret = `${prefix} {${type}} ${key}\n`
// 若是數(shù)組展蒂,將遞歸執(zhí)行g(shù)enerateFieldDoc
for (let attr in value) {
ret += generateFieldDoc(`${key}.${attr}`, value[attr])
}
return ret
}
總得來說,借助apidoc生成model文檔,是可以滿足查看的需求悼泌,而且顯示上可以與接口文檔存放在同一位置統(tǒng)一查看隘世,不過在顯示效果上可以缺失了索引等屬性鸠踪。