1. 程式人生 > >nodejs結合apiblue實現MockServer

nodejs結合apiblue實現MockServer

ret 業務 接口 www. 無法更新 locals 代碼 resolv 文件夾

apiblue功能很強大,裏面支持很多插件,這些插件能夠為restfulAPI提供接口文檔自動生成,甚至Mockserver的功能,當然,好多插件還是有很多坑的。下面用apiblue實現下面的業務需求:

1、用戶上傳.md文件,自動啟動mock動作,生成一套api測試服務

2、根據.md文檔自動生成html接口文檔

3、當.md文檔發生crud操作的時候,文檔和mockServer自動更新

drakov將.md文檔中的接口自動生成Mockserver,關鍵代碼如下:

 1 var drakov = require(‘drakov‘);
 2 var aglio = require(‘./aglio‘
); 3 var path = require(‘path‘); 4 var sourceFiles = path.resolve(__dirname, ‘../mfiles/**.md‘); 5 var fs = require("fs"); 6 var argv = { 7 sourceFiles: sourceFiles,//md文檔存儲地 8 serverPort: 4007, 9 disableCORS: false,//false允許跨域訪問 10 debugMode: true, 11 discover: true, 12 public: true
,//true允許外圍ip訪問api,false只能本地訪問 13 watch: true, 14 method: [‘GET‘, ‘PUT‘, ‘POST‘, ‘DELETE‘, ‘OPTIONS‘] 15 }; 16 module.exports = function (mdFileUrl) { 17 try { 18 if ((mdFileUrl && typeof (mdFileUrl) === "string" && mdFileUrl.indexOf(".md") > -1) || mdFileUrl == ‘‘) {
19 drakov.stop(function () { 20 // stopped Drakov 21 console.log(‘drakov Finished‘); 22 }); 23 24 drakov.run(argv, function () { 25 console.log(‘drakov start‘); 26 }); 27 if (mdFileUrl) { 28 aglio(mdFileUrl); 29 } 30 } 31 32 } catch (e) { } finally { } 33 }

https://github.com/Aconex/drakov 這是drakov git地址,上面介紹了使用中間件的方式實現drakov與express結合,當時有問題,drakov的watch功能失效,md文檔發生改變,無法更新apiServer。

aglio實現將md文檔生成HTML接口文檔,關鍵代碼如下:
 1 var aglio = require(‘aglio‘);
 2 var path = require(‘path‘);
 3 var fs = require(‘fs‘);
 4 var aglio_options = {
 5   themeTemplate: ‘default‘,//aglio樣式
 6   locals: {
 7     myVariable: 125
 8   }
 9 };
10 module.exports = function(mdFileUrl) {
11   if (mdFileUrl) {
12     var targetUrl = mdFileUrl.replace("/mfiles/", "/mock-ui/").replace(".md", ".html");
13     aglio.renderFile(mdFileUrl, targetUrl, aglio_options, function(err, warnings) {
14       if (err)
15         return console.log(err);
16       }
17     );
18   }
19 
20 }

watch監控存放md文件的文件夾,實時通知drakov和aligo,關鍵代碼如下:

 1 var watch = require(‘watch‘);
 2 var drakov = require(‘./drakov‘);
 3 
 4 module.exports = function (watchDir) {
 5   try {
 6     var filepath;
 7     watch.watchTree(watchDir, function (f, curr, prev) {
 8       if (typeof f == "object" && prev === null && curr === null) {
 9         // Finished walking the tree
10         drakov(‘‘)
11       } else if (prev === null) {
12         // f is a new file
13         if (filepath != f) {
14           drakov(f, ‘new‘);
15           filepath = f;
16         }
17       } else if (curr.nlink === 0) {
18         if (filepath != f) {
19           // f was removed
20           drakov(f)
21         }
22       } else {
23         // f was changed
24         drakov(f)
25       }
26     })
27     console.log("watching file...");
28 
29   } catch (e) {
30     console.log(e.message);
31   } finally { }
32 
33 }

ok 根據這三個js,你就可以建一個MockServer,就像 easymock(www.easy-mock.com)一樣,試試吧。。對於需求工程師很有幫助

歡迎關註我的訂閱號

技術分享

nodejs結合apiblue實現MockServer