国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

淺談KOA2 Restful方式路由初探

2024-05-06 15:41:40
字體:
來源:轉載
供稿:網友

前言

最近考慮將服務器資源整合一下,作為多端調用的API

看到Restful標準和ORM眼前一亮,但是找了不少版本路由寫的都比較麻煩,于是自己折騰了半天

API庫結構

考慮到全部對象置于頂層將會造成對象名越來長,同時不便于維護,故采取部分的分層結構

如workflow模塊內的prototypes,instances等等,分層的深度定義為層級

可訪問的對象集合(collection)的屬性滿足Restful設計

 -- workflow(category)  -- prototypes(collection)    -- [method] ...    -- [method] ...   -- instances(collection) -- users(collection)   --[method] List     #get :object/   --[method] Instance   #get :object/:id -- ... -- ...

RESTFUL API 接口

將Restful API接口進行標準化命名

.get('/', ctx=>{ctx.error('路徑匹配失敗')})        .get('/:object', RestfulAPIMethods.List).get('/:object/:id', RestfulAPIMethods.Get).post('/:object', RestfulAPIMethods.Post).put('/:object/:id', RestfulAPIMethods.Replace).patch('/:object/:id', RestfulAPIMethods.Patch).delete('/:object/:id', RestfulAPIMethods.Delete).get('/:object/:id/:related', RestfulAPIMethods.Related).post('/:object/:id/:related', RestfulAPIMethods.AddRelated).delete('/:object/:id/:related/:relatedId', RestfulAPIMethods.DelRelated)

API對象

這個文件是來自微信小程序demo,覺得很方便就拿來用了,放于需要引用的根目錄,引用后直接獲得文件目錄結構API對象

const _ = require('lodash')const fs = require('fs')const path = require('path')/** * 映射 d 文件夾下的文件為模塊 */const mapDir = d => {  const tree = {}  // 獲得當前文件夾下的所有的文件夾和文件  const [dirs, files] = _(fs.readdirSync(d)).partition(p => fs.statSync(path.join(d, p)).isDirectory())  // 映射文件夾  dirs.forEach(dir => {    tree[dir] = mapDir(path.join(d, dir))  })  // 映射文件  files.forEach(file => {    if (path.extname(file) === '.js') {      tree[path.basename(file, '.js')] = require(path.join(d, file))      tree[path.basename(file, '.js')].isCollection = true    }  })  return tree}// 默認導出當前文件夾下的映射module.exports = mapDir(path.join(__dirname))

koa-router分層路由的實現

創建多層路由及其傳遞關系

執行順序為

 1 -- 路徑匹配
    -- 匹配到‘/'結束
    -- 匹配到對應的RestfulAPI執行并結束
    -- 繼續
 2 -- 傳遞中間件 Nest
 3 -- 下一級路由
 4 -- 循環 to 1

const DefinedRouterDepth = 2let routers = []for (let i = 0; i < DefinedRouterDepth; i++) {  let route = require('koa-router')()  if (i == DefinedRouterDepth - 1) {    // 嵌套路由中間件    route.use(async (ctx, next) => {      // 根據版本號選擇庫      let apiVersion = ctx.headers['api-version']      ctx.debug(`------- (API版本 [${apiVersion}]) --=-------`)       if (!apiVersion) {        ctx.error('版本號未標記')        return      }      let APIRoot = null      try {        APIRoot = require(`../restful/${apiVersion}`)      } catch (e) {        ctx.error ('API不存在,請檢查Header中的版本號')        return      }      ctx.debug(APIRoot)      ctx.apiRoot = APIRoot      ctx.debug('---------------------------------------------')      // for(let i=0;i<)      await next()    })  }  route    .get('/', ctx=>{ctx.error('路徑匹配失敗')})    .get('/:object', RestfulAPIMethods.List)    .get('/:object/:id', RestfulAPIMethods.Get)    .post('/:object', RestfulAPIMethods.Post)    .put('/:object/:id', RestfulAPIMethods.Replace)    .patch('/:object/:id', RestfulAPIMethods.Patch)    .delete('/:object/:id', RestfulAPIMethods.Delete)    .get('/:object/:id/:related', RestfulAPIMethods.Related)    .post('/:object/:id/:related', RestfulAPIMethods.AddRelated)    .delete('/:object/:id/:related/:relatedId', RestfulAPIMethods.DelRelated)  if (i != 0) {    route.use('/:object', Nest, routers[i - 1].routes())  }  routers.push(route)}let = router = routers[routers.length - 1]            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 张掖市| 石阡县| 门源| 清远市| 偏关县| 朝阳县| 新绛县| 灌阳县| 洛阳市| 容城县| 西安市| 介休市| 彭泽县| 长武县| 丽水市| 嘉祥县| 梨树县| 信丰县| 德清县| 太仓市| 土默特左旗| 葫芦岛市| 姚安县| 鲁甸县| 峡江县| 渭南市| 石屏县| 平凉市| 洛扎县| 商丘市| 旬邑县| 辽阳县| 遂宁市| 江孜县| 武汉市| 周宁县| 大城县| 崇阳县| 横山县| 满城县| 兴业县|