koa router multi file introduction

Keywords: Javascript JSON npm

background

There are more and more koa router routes. The router under api needs to be introduced in the following way. How can all files under api be introduced conveniently and quickly
This time, it is recorded that if the koa router one-time loop is introduced

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())
//...

File directory

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

Introducing router in traditional way

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 introduction

Require directory is used to recursively iterate over the specified directories and return these modules.
github
With the increase of files, how to develop efficiently is what we should pursue

First

npm install require-directory

app.js

const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
// Use require directory to load all router s under the routing folder
const requireDirectory = require('require-directory')

// Load all routes and load code automatically
const modules = requireDirectory(module, './api', { visit: whenLoadModule })

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

app.listen(3333)

Routing files are written in the traditional way
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

About me

You can scan and add the wechat below and note Soul plus exchange group, give me opinions, exchange and learn.

If I can help you, send me a little star

Reprint please contact the author!

Posted by cjosephson on Wed, 06 Nov 2019 09:23:42 -0800