koa router 多文件引入的方法示例

èæ¯

koa-routerè·¯ç±è¶æ¥è¶å¤,apiä¸çrouteré½è¦ä½¿ç¨ä¸é¢çæ¹å¼å¼å¥,æä¹æè½æ¹ä¾¿å¿«æ·çå°apiä¸çæææ件é½å¼å¥å¢
è¿æ¬¡è®°å½çå°±æ¯å¦æå°koa-router ä¸æ¬¡æ§å¾ªç¯å¼å¥

const book = require('./app/api/v1/book')
const classic = require('./app/api/v1/classic')
// ...
app.use(book.routes(), book.allowedMethods())
app.use(classic.routes(), classic.allowedMethods())
//...

æ件ç®å½

koa-demo/
 |-api/
  |-books.js
  |-classic.js
  |-users.js
  |-articles.js
 |-package.json
 |-app.js

ä¼ ç»æ¹å¼å¼å¥router

app.js

const Koa = require('koa')
const app = new Koa()
const book = require('./app/api/v1/book')
const classic = require('./app/api/v1/classic')

app.use(book.routes(), book.allowedMethods())
app.use(classic.routes(), classic.allowedMethods())

app.listen(3333)

require-directoryå¼å¥

require-directoryç¨æ¥éå½å°è¿­ä»£æå®çç®å½ï¼å¹¶è¿åè¿äºæ¨¡åã

github

éçæ件å¢å ï¼å¦ä½é«æçå¼åå°±æ¯æ们è¦è¿½æ±çäºæäº

é¦å

npm install require-directory

app.js

const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
// 使ç¨require-directoryå è½½è·¯ç±æ件夹ä¸çæærouter
const requireDirectory = require('require-directory')

// å°ææçè·¯ç±å è½½ä¸,èªå¨å è½½ä»£ç 
const modules = requireDirectory(module, './api', { visit: whenLoadModule })

function whenLoadModule(obj) {
 if (obj instanceof Router) {
 app.use(obj.routes(), obj.allowedMethods())
 }
}

app.listen(3333)

è·¯ç±æ件就æç§ä¼ ç»çæ¹å¼åå°±è¡

books.js

const Router = require('koa-router')
const router = new Router()

router.get('/v1/book/latest', (ctx, next) => {
 ctx.body = {
  key: 'book'
 }
})

module.exports = router

以ä¸å°±æ¯æ¬æçå¨é¨å容ï¼å¸æ对大家ç学习ææ帮å©ï¼ä¹å¸æ大家å¤å¤æ¯æèæ¬ä¹å®¶ã

相关推荐