The router layer

  1. Defining the Routing Layer

Routes/index. Js file

module.exports ={
  'get /':async ctx =>{
     ctx.body = 'home'
  },
  'get /detail':async ctx =>{
      ctx.body = 'Home Page Details'}},Copy the code
  1. Implement loader to read files in Routes
const fs = require('fs')
const path = require('path')
const Router = require('koa-router')

// Used to load directories
function load(dir,cb){
    // Get the absolute directory address
  const dirPath = path.resolve(__dirname,dir)
  // Read the folder
   const files = fs.readdirSync(dirPath)
   files.forEach((filename) = >{
        // Remove the file suffix and record the file name
        filename = filename.replace('.js'.' ')
        // Load the file contents
        const file = require(dirPath+ '/'+filename)
        // file name File content
        cb(filename,file)
    }) 
}
// Initialize the route
function initRouter() {
   const router = new Router()
   load('routes'.(filename, file) = > {
    // Check whether the file name in routes is index. If not, it is the current file name
    const prefix = filename === 'index'? ' ' : ` /${filename}`
    // Parse the contents of file
    // The file is an object, so get the file object, take the corresponding key
    Object.keys(file).forEach((key) = > {
    // Parse the key value
    const [method,path] = key.split(' ')
    // Register the route
    router[method](prefix + path, file[key])
    })
})
   return router 
}

module.exports = {initRouter}
Copy the code

index.js

const koa = require('koa')
const {initRouter} = require('./loader')

class MyEgg{
    constructor(){
        this.$app = new koa()
        this.$router = initRouter()
        this.$app.use(this.$router.routes())
    }
    start(port){
        this.$app.listen(port,() = >{
            console.log('Server started')}}}module.exports = MyEgg
Copy the code

main.js

const myEgg = require('./index')

const app = new myEgg()

app.start(4000)
Copy the code

Thus we implement the Route layer

To realize the controller layer

controller

module.exports = {
    info:async ctx =>{
       ctx.body = 'User details page'
    },
    index:async ctx =>{
        ctx.body = 'the user home page Controller'}}Copy the code

Call controller from router (added parameter APP)

module.exports = app= >  ({
    'get /':app.$ctrl.user.index, 
    'get /info':app.$ctrl.user.info 
})
Copy the code

So let’s implement a Controller loader(and modify the router here)

const fs = require('fs') const path = require('path') const Router = require('koa-router') const { type } = Function load(dir,cb){const dirPath = path.resolve(__dirname,dir) const dirPath = path.resolve(__dirname,dir File = fs.readdirsync (dirPath) files.foreach ((filename)=>{// Remove the file suffix, File name filename = filename.replace('.js','') // Load file content const file = require(dirPath+ '/'+filename) // filename File content Cb (filename,file)})} function initRouter(app) {const router = new router () load('routes',(filename, File) => {// check whether the file name in routes is index. If not, the current filename const prefix = filename === 'index'? '' : '/${filename}' // parse the contents of file // to judge file. It could be a function. File = typeof file === 'function'? file(app) : File // Since the file is an object, get the file object, Keys (file).foreach ((key) => {// Parse the key const [method,path] = key.split(' ') // register the route router[method](prefix + path, File [key])})}) return router} function initController() {const controllers = {} load('controller',(filename,controller)=>{ controllers[filename] = controller }) return controllers } module.exports = {initRouter,initController}Copy the code

So we’ve implemented a Controller layer

Implement the service layer

service

const delay = (data,tick) = >new Promise(resolve= >{
    setTimeout(() = > {
        resolve(data)
    }, tick);
})


module.exports = {
    getName(){
        return delay('jerry'.1000)},getAge(){
       return 20}}Copy the code

The Service layer can be called either directly by the Router or by the Controller layer. So we’re going to change the Controller and service

const fs = require('fs')
const path = require('path')
const Router = require('koa-router')
const { type } = require('os')

// Used to load directories
function load(dir,cb){
    // Get the absolute directory address
  const dirPath = path.resolve(__dirname,dir)
  // Read the folder
   const files = fs.readdirSync(dirPath)
   files.forEach((filename) = >{
        // Remove the file suffix and record the file name
        filename = filename.replace('.js'.' ')
        // Load the file contents
        const file = require(dirPath+ '/'+filename)
        // file name File content
        cb(filename,file)
    }) 
}
// Initialize the route
function initRouter(app) {
   const router = new Router()
   load('routes'.(filename, file) = > {
    // Check whether the file name in routes is index. If not, it is the current file name
    const prefix = filename === 'index'? ' ' : ` /${filename}`
    // Parse the contents of file

    // To judge file. It could be a function. It could be an object
    file = typeof file === 'function'? file(app) : file

    // The file is an object, so get the file object, take the corresponding key
    Object.keys(file).forEach((key) = > {
    // Parse the key value
    const [method,path] = key.split(' ')
    // Register the route
    router[method](prefix + path, async(ctx)=>{
        app.ctx = ctx
        await file[key](app)
    })
    })
})
   return router 
}


function initController(app) {
    // Group by name
    const controllers = {}
    load('controller'.(filename,controller) = >{
        controllers[filename] = controller(app)
    })
    return controllers
 }
 function initService() {
    const services = {}
    load('service'.(filename,service) = >{
        services[filename] = service
    })
    return services
}



module.exports = {initRouter,initController, initService}
Copy the code

index.js

const koa = require('koa')
const {initRouter, initController, initService} = require('./loader')

class MyEgg{
    constructor() {
        this.$app = new koa()
        this.$service = initService()
        this.$ctrl = initController(this)
        this.$router = initRouter(this)
        this.$app.use(this.$router.routes())
    }
    start(port){
        this.$app.listen(port, () = > {
            console.log('Server started')}}}module.exports = MyEgg
Copy the code

Thus we implement the Service layer

Finally, about config configuration, middle key and so on, you can also implement it yourself. The principle is similar to above warehouse address: github.com/yujun96/mye…