自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

像Vue-Router一樣配置Node路由?

開發(fā) 前端 商務(wù)辦公
前后端分離后,前端童鞋會需要處理一些node層的工作,比如模板渲染、接口轉(zhuǎn)發(fā)、部分業(yè)務(wù)邏輯等,比較常用的框架有koa、koa-router等。

 [[440238]]

本文轉(zhuǎn)載自微信公眾號「前端胖頭魚」,作者前端胖頭魚 。轉(zhuǎn)載本文請聯(lián)系前端胖頭魚公眾號。

前言

前后端分離后,前端童鞋會需要處理一些node層的工作,比如模板渲染、接口轉(zhuǎn)發(fā)、部分業(yè)務(wù)邏輯等,比較常用的框架有koa、koa-router等。

現(xiàn)在我們需要實現(xiàn)這樣一個需求:

  • 用戶訪問/fe的時候,頁面展示hello fe
  • 用戶訪問/backend的時候,頁面展示hello backend

你是不是在想,這需求俺根本不用koa、koa-router,原生的node模塊就可以搞定。

  1. const http = require('http'
  2. const url = require('url'
  3. const PORT = 3000 
  4.  
  5. http.createServer((req, res) => { 
  6.   let { pathname } = url.parse(req.url) 
  7.   let str = 'hello' 
  8.  
  9.   if (pathname === '/fe') { 
  10.     str += ' fe' 
  11.   } else if (pathname === '/backend') { 
  12.     str += ' backend' 
  13.   } 
  14.  
  15.   res.end(str) 
  16. }).listen(PORT, () => { 
  17.   console.log(`app start at: ${PORT}`) 
  18. }) 

確實是,對于很簡單的需求,用上框架似乎有點浪費(fèi),但是對于以上的實現(xiàn),也有缺點存在,比如

  • 需要我們自己去解析路徑。
  • 路徑的解析和邏輯的書寫耦合在一塊。如果未來有更多更復(fù)雜的需求需要實現(xiàn),那就gg了。

所以接下來我們來試試用koa和koa-router怎么實現(xiàn)

app.js

  1. const Koa = require('koa'
  2. const KoaRouter = require('koa-router'
  3.  
  4. const app = new Koa() 
  5. const router = new KoaRouter() 
  6. const PORT = 3000 
  7.  
  8. router.get('/fe', (ctx) => { 
  9.   ctx.body = 'hello fe' 
  10. }) 
  11.  
  12. router.get('/backend', (ctx) => { 
  13.   ctx.body = 'hello backend' 
  14. }) 
  15.  
  16. app.use(router.routes()) 
  17. app.use(router.allowedMethods()) 
  18.  
  19. app.listen(PORT, () => { 
  20.   console.log(`app start at: ${PORT}`) 
  21. }) 

通過上面的處理,路徑的解析倒是給koa-router處理了,但是整體的寫法還是有些問題。

  • 匿名函數(shù)的寫法沒有辦法復(fù)用
  • 路由配置和邏輯處理在一個文件中,沒有分離,項目一大起來,同樣是件麻煩事。

接下來我們再優(yōu)化一下,先看一下整體的目錄結(jié)構(gòu)

  1. ├──app.js // 應(yīng)用入口 
  2. ├──controller // 邏輯處理,分模塊 
  3. │   ├──hello.js 
  4. │   ├──aaaaa.js 
  5. ├──middleware // 中間件統(tǒng)一注冊 
  6. │   ├──index.js 
  7. ├──routes // 路由配置,可以分模塊配置 
  8. │   ├──index.js 
  9. ├──views // 模板配置,分頁面或模塊處理,在這個例子中用不上 
  10. │   ├──index.html 

預(yù)覽一下每個文件的邏輯

app.js 應(yīng)用的路口

  1. const Koa = require('koa'
  2. const middleware = require('./middleware'
  3. const app = new Koa() 
  4. const PORT = 3000 
  5.  
  6. middleware(app) 
  7.  
  8. app.listen(PORT, () => { 
  9.   console.log(`app start at: ${PORT}`) 
  10. }) 

routes/index.js 路由配置中心

  1. const KoaRouter = require('koa-router'
  2. const router = new KoaRouter() 
  3. const koaCompose = require('koa-compose'
  4. const hello = require('../controller/hello'
  5.  
  6. module.exports = () => { 
  7.   router.get('/fe', hello.fe) 
  8.   router.get('/backend', hello.backend) 
  9.  
  10.   return koaCompose([ router.routes(), router.allowedMethods() ]) 

controller/hello.js hello 模塊的邏輯

  1. module.exports = { 
  2.   fe (ctx) { 
  3.     ctx.body = 'hello fe' 
  4.   }, 
  5.   backend (ctx) { 
  6.     ctx.body = 'hello backend' 
  7.   } 

middleware/index.js 中間件統(tǒng)一注冊

  1. const routes = require('../routes'
  2.  
  3. module.exports = (app) => { 
  4.   app.use(routes()) 

寫到這里你可能心里有個疑問?一個簡單的需求,被這么一搞看起來復(fù)雜了太多,有必要這樣么?

答案是:有必要,這樣的目錄結(jié)構(gòu)或許不是最合理的,但是路由、控制器、view層等各司其職,各在其位。對于以后的擴(kuò)展有很大的幫助。

不知道大家有沒有注意到路由配置這個地方

routes/index.js 路由配置中心

  1. const KoaRouter = require('koa-router'
  2. const router = new KoaRouter() 
  3. const koaCompose = require('koa-compose'
  4. const hello = require('../controller/hello'
  5.  
  6. module.exports = () => { 
  7.   router.get('/fe', hello.fe) 
  8.   router.get('/backend', hello.backend) 
  9.  
  10.   return koaCompose([ router.routes(), router.allowedMethods() ]) 

每個路由對應(yīng)一個控制器去處理,很分離,很常見啊!!!這似乎也是我們平時在前端寫vue-router或者react-router的常見配置模式。

但是當(dāng)模塊多起來的來時候,這個文件夾就會變成

  1. const KoaRouter = require('koa-router'
  2. const router = new KoaRouter() 
  3. const koaCompose = require('koa-compose'
  4. // 下面你需要require各個模塊的文件進(jìn)來 
  5. const hello = require('../controller/hello'
  6. const a = require('../controller/a'
  7. const c = require('../controller/c'
  8.  
  9. module.exports = () => { 
  10.   router.get('/fe', hello.fe) 
  11.   router.get('/backend', hello.backend) 
  12.   // 配置各個模塊的路由以及控制器 
  13.   router.get('/a/a', a.a) 
  14.   router.post('/a/b', a.b) 
  15.   router.get('/a/c', a.c) 
  16.   router.get('/a/d', a.d) 
  17.  
  18.   router.get('/c/a', c.c) 
  19.   router.post('/c/b', c.b) 
  20.   router.get('/c/c', c.c) 
  21.   router.get('/c/d', c.d) 
  22.  
  23.   // ... 等等     
  24.   return koaCompose([ router.routes(), router.allowedMethods() ]) 

有沒有什么辦法,可以讓我們不用手動引入一個個控制器,再手動的調(diào)用koa-router的get post等方法去注冊呢?

比如我們只需要做以下配置,就可以完成上面手動配置的功能。

routes/a.js

  1. module.exports = [ 
  2.   { 
  3.     path: '/a/a'
  4.     controller: 'a.a' 
  5.   }, 
  6.   { 
  7.     path: '/a/b'
  8.     methods: 'post'
  9.     controller: 'a.b' 
  10.   }, 
  11.   { 
  12.     path: '/a/c'
  13.     controller: 'a.c' 
  14.   }, 
  15.   { 
  16.     path: '/a/d'
  17.     controller: 'a.d' 
  18.   } 

routes/c.js

  1. module.exports = [ 
  2.   { 
  3.     path: '/c/a'
  4.     controller: 'c.a' 
  5.   }, 
  6.   { 
  7.     path: '/c/b'
  8.     methods: 'post'
  9.     controller: 'c.b' 
  10.   }, 
  11.   { 
  12.     path: '/c/c'
  13.     controller: 'c.c' 
  14.   }, 
  15.   { 
  16.     path: '/c/d'
  17.     controller: 'c.d' 
  18.   } 

然后使用pure-koa-router這個模塊進(jìn)行簡單的配置就ok了

  1. const pureKoaRouter = require('pure-koa-router'
  2. const routes = path.join(__dirname, '../routes') // 指定路由 
  3. const controllerDir = path.join(__dirname, '../controller') // 指定控制器的根目錄 
  4.  
  5. app.use(pureKoaRouter({ 
  6.   routes, 
  7.   controllerDir 
  8. })) 

這樣整個過程我們的關(guān)注點都放在路由配置上去,再也不用去手動require一堆的文件了。

簡單介紹一下上面的配置

  1.   path: '/c/b'
  2.   methods: 'post'
  3.   controller: 'c.b' 

path: 路徑配置,可以是字符串/c/b,也可以是數(shù)組[ '/c/b' ],當(dāng)然也可以是正則表達(dá)式/\c\b/

methods: 指定請求的類型,可以是字符串get或者數(shù)組[ 'get', 'post' ],默認(rèn)是get方法,

controller: 匹配到路由的邏輯處理方法,c.b 表示controllerDir目錄下的c文件導(dǎo)出的b方法,a.b.c表示controllerDir目錄下的/a/b 路徑下的b文件導(dǎo)出的c方法

源碼實現(xiàn)

接下來我們逐步分析一下實現(xiàn)邏輯

可以點擊查看源碼

整體結(jié)構(gòu)

  1. module.exports = ({ routes = [], controllerDir = '', routerOptions = {} }) => { 
  2.   // xxx 
  3.  
  4.   return koaCompose([ router.routes(), router.allowedMethods() ]) 
  5. }) 

pure-koa-router接收

1.routes

  • 可以指定路由的文件目錄,這樣pure-koa-router會去讀取該目錄下所有的文件 (const routes = path.join(__dirname, '../routes'))
  • 可以指定具體的文件,這樣pure-koa-router讀取指定的文件內(nèi)容作為路由配置 const routes = path.join(__dirname, '../routes/tasks.js')
  • 可以直接指定文件導(dǎo)出的內(nèi)容 (const routes = require('../routes/index'))

2.controllerDir、控制器的根目錄

3.routerOptions new KoaRouter時候傳入的參數(shù),具體可以看koa-router

這個包執(zhí)行之后會返回經(jīng)過koaCompose包裝后的中間件,以供koa實例添加。

參數(shù)適配

  1. assert(Array.isArray(routes) || typeof routes === 'string''routes must be an Array or a String'
  2. assert(fs.existsSync(controllerDir), 'controllerDir must be a file directory'
  3.  
  4. if (typeof routes === 'string') { 
  5.   routes = routes.replace('.js'''
  6.  
  7.   if (fs.existsSync(`${routes}.js`) || fs.existsSync(routes)) { 
  8.     // 處理傳入的是文件 
  9.     if (fs.existsSync(`${routes}.js`)) { 
  10.       routes = require(routes) 
  11.     // 處理傳入的目錄   
  12.     } else if (fs.existsSync(routes)) { 
  13.       // 讀取目錄中的各個文件并合并 
  14.       routes = fs.readdirSync(routes).reduce((result, fileName) => { 
  15.         return result.concat(require(nodePath.join(routes, fileName))) 
  16.       }, []) 
  17.     } 
  18.   } else { 
  19.     // routes如果是字符串則必須是一個文件或者目錄的路徑 
  20.     throw new Error('routes is not a file or a directory'
  21.   } 

路由注冊

不管routes傳入的是文件還是目錄,又或者是直接導(dǎo)出的配置的內(nèi)容最后的結(jié)構(gòu)都是是這樣的

routes內(nèi)容預(yù)覽

  1.   // 最基礎(chǔ)的配置 
  2.   { 
  3.     path: '/test/a'
  4.     methods: 'post'
  5.     controller: 'test.index.a' 
  6.   }, 
  7.   // 多路由對一個控制器 
  8.   { 
  9.     path: [ '/test/b''/test/c' ], 
  10.     controller: 'test.index.a' 
  11.   }, 
  12.   // 多路由對多控制器 
  13.   { 
  14.     path: [ '/test/d''/test/e' ], 
  15.     controller: [ 'test.index.a''test.index.b' ] 
  16.   }, 
  17.   // 單路由對對控制器 
  18.   { 
  19.     path: '/test/f'
  20.     controller: [ 'test.index.a''test.index.b' ] 
  21.   }, 
  22.   // 正則 
  23.   { 
  24.     path: /\/test\/\d/, 
  25.     controller: 'test.index.c' 
  26.   } 

主動注冊

  1. let router = new KoaRouter(routerOptions) 
  2. let middleware 
  3.  
  4. routes.forEach((routeConfig = {}) => { 
  5.   let { path, methods = [ 'get' ], controller } = routeConfig 
  6.   // 路由方法類型參數(shù)適配 
  7.   methods = (Array.isArray(methods) && methods) || [ methods ] 
  8.   // 控制器參數(shù)適配 
  9.   controller = (Array.isArray(controller) && controller) || [ controller ] 
  10.  
  11.   middleware = controller.map((controller) => { 
  12.     // 'test.index.c' => [ 'test''index''c' ] 
  13.     let controllerPath = controller.split('.'
  14.     // 方法名稱 c 
  15.     let controllerMethod = controllerPath.pop() 
  16.  
  17.     try { 
  18.       // 讀取/test/index文件的c方法 
  19.       controllerMethod = require(nodePath.join(controllerDir, controllerPath.join('/')))[ controllerMethod ] 
  20.     } catch (error) { 
  21.       throw error 
  22.     } 
  23.     // 對讀取到的controllerMethod進(jìn)行參數(shù)判斷,必須是一個方法 
  24.     assert(typeof controllerMethod === 'function''koa middleware must be a function'
  25.  
  26.     return controllerMethod 
  27.   }) 
  28.   // 最后使用router.register進(jìn)行注冊 
  29.   router.register(path, methods, middleware) 

源碼的實現(xiàn)過程基本就到這里了。

結(jié)尾

pure-koa-router將路由配置和控制器分離開來,使我們將注意力放在路由配置和控制器的實現(xiàn)上。希望對您能有一點點幫助。

 

責(zé)任編輯:武曉燕 來源: 前端胖頭魚
相關(guān)推薦

2023-04-05 14:19:07

FlinkRedisNoSQL

2022-09-09 18:59:28

Vue類型枚舉

2022-02-02 21:29:39

路由模式Vue-Router

2013-12-31 09:19:23

Python調(diào)試

2013-12-17 09:02:03

Python調(diào)試

2022-12-21 15:56:23

代碼文檔工具

2023-05-23 13:59:41

RustPython程序

2021-11-11 08:20:47

Vue 技巧 開發(fā)工具

2015-03-16 12:50:44

2013-08-22 10:17:51

Google大數(shù)據(jù)業(yè)務(wù)價值

2021-05-20 08:37:32

multiprocesPython線程

2011-01-18 10:45:16

喬布斯

2012-06-08 13:47:32

Wndows 8Vista

2015-02-05 13:27:02

移動開發(fā)模塊SDK

2012-03-21 10:15:48

RIM越獄

2021-09-07 10:29:11

JavaScript模塊CSS

2017-05-22 10:33:14

PythonJuliaCython

2011-10-24 13:07:00

2012-06-14 09:48:11

OpenStackLinux

2015-04-09 11:27:34

點贊
收藏

51CTO技術(shù)棧公眾號