前言项目正式版已经发布。最近,我过得比较悠闲。闲逛的时候看到了rsshub库。想玩玩,但是rsshub文档里面的接口太多了。一时兴起,解析rsshub的文档,自动生成文档中出现的所有API,供前端页面使用。不是什么原因导致我的yarn和npm都安装不了rsshub包。我只是拉取GitHub的rsshub并使用它。如果能安装,直接安装即可。如果装不上,可以像我一样拆下来使用。项目地址rsshub-demo效果图没有具体写样式,部分接口有问题,可能获取不到数据代码。首先,第一步也是最核心的一步是解析文档并提取有效信息。当然,使用正则表达式来解析对应的API名称、标题、路径等,我先定义了一个常量来声明这些正则规则。constRegMap={类型:newRegExp(/\s#\s(.+)\s/g),内容:newRegExp(/\s##.+\s??+###.+\s??+()|(<\/Route>\s+###.+\s??+)/g),标题:newRegExp(/\s##\s(.+)\s/g),ChildTitle:newRegExp(/\s###(.+)/g),Route:newRegExp(/(\)/g),Example:newRegExp(/example="(\S+)"/g),路径:newRegExp(/path="(\S+)"/g),ParamsDesc:newRegExp(/paramsDesc="(.+)"/g),};解析文档内容,这里我直接下载了文档,大家也可以请求文档进行解析,查找有效信息的代码有点low,解析后生成一个json文件,里面有接口的具体标题、路径等信息让类型;constdata=awaitfs.readFileSync(join(__dirname,`../../docs/${file}`)).toString();data.replace(RegMap.Type,(_,val)=>(type=val));constlist=data.match(RegMap.Content);如果(!列表)返回;常量结果=[];for(letindex=0;index(山雀le=val));content.replace(RegMap.ChildTitle,(_,val)=>(childTitle=val));content.replace(RegMap.Route,(_,val)=>(route=val));if(route){route.replace(RegMap.Example,(_,val)=>(example=val));route.replace(RegMap.Path,(_,val)=>(path=val));route.replace(RegMap.ParamsDesc,(_,val)=>(paramsDesc=val));}if(title){result.push({title,children:[{title:childTitle,example,path,paramsDesc,},],});}else{constparent=getParent(result,index);if(parent){parent.children.push({title:childTitle,example,path,paramsDesc,});}}}fs.writeFileSync(`./api/${file}.json`,JSON.stringify({type,result}));读取生成的接口信息json文件constapiPath=join(__dirname,"../api");constfiles=awaitfs.readdirSync(apiPath);files.forEach(async(file)=>{constdata=awaitfs.readFileSync(join(apiPath,file)).toString();routeList.push(JSON.parse(data));});使用express创建一个服务,读取并处理接口json,配置相应的后端api,提供routeList给前端页面,方便直接从页面获取其他接口。constexpress=require("express");constRSSHub=require("./RSSHub/lib/pkg");constapp=express();constcreateRoute=require("./utils/create-route");函数GetData(url){returnnewPromise((res,rej)=>{RSSHub.init({});RSSHub.request(`https://rsshub.app${url}`).then(res).catch(rej);});}app.use(express.static("./static"));constlist=[];awaitcreateRoute(list);constrouteList=list.map((v)=>v.结果).flat().map((v)=>v.children).flat();//配置apirouteList.forEach((route)=>{app.get(`/api${route.example}`,asyncfunction(req,res){constdata=awaitGetData(route.example);res.send(data.item);});});//给前端提供一个routeList,方便前端调用其他接口app.get("/api/alldata",(req,res)=>{res.send(list);});app.listen(8088,()=>{console.log("http://localhost:8088端口启动".green);});页面使用axios发起请求,使用petite-vue快速传播数据<脚本src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js">{{item.type}}