Video address: www.cctalk.com/v/151149238…

The article

In the previous sections, we have implemented several common operations in a project: starting a server, routing middleware, request processing in the form of Get and Post, and so on. Now you have taken the first step towards success.

For now, all the code in the entire example is in app.js. However, as the business code continues to grow and the scene becomes more complex, this approach is not good for post-maintenance or students with OBSessive-compulsive disorder. So here’s what we’re going to do: Divide the pears.

The separation of the router

The routing code can be separated into a separate file and placed in the project root directory or in a separate Router folder, depending on your preference. In this case, we’ll name it router.js and place it in the root directory.

Example Modify the router.js route

  const router = require('koa-router') ()module.exports = (app) = > {
    router.get('/'.async(ctx, next) => {
      ctx.response.body = `<h1>index page</h1>`
    })
    
    router.get('/home'.async(ctx, next) => {
      console.log(ctx.request.query)
      console.log(ctx.request.querystring)
      ctx.response.body = '<h1>HOME page</h1>'
    })
    
    router.get('/home/:id/:name'.async(ctx, next)=>{
      console.log(ctx.params)
      ctx.response.body = '<h1>HOME page /:id/:name</h1>'
    })
    
    router.get('/user'.async(ctx, next)=>{
      ctx.response.body = 
      
      




}) // Add a route that responds to the form request router.post('/user/register'.async(ctx, next)=>{ let {name, password} = ctx.request.body if( name == 'ikcamp' && password == '123456' ){ ctx.response.body = ` Hello,${name}! ` }else{ ctx.response.body = 'Account information error' } }) app.use(router.routes()) .use(router.allowedMethods()) } Copy the code

Modify the app. Js

  const Koa = require('koa')
  const bodyParser = require('koa-bodyparser')
  const app = new Koa()
  const router = require('./router')

  app.use(bodyParser())

  router(app)

  app.listen(3000, () = > {console.log('server is running at http://localhost:3000')})Copy the code

The code looks much cleaner.

At this point, however, there is no rest assured. With the router file isolated, the app’s main file app.js looks cleaner for a while, but this is when there is only one route and the handling function is very simple. If there are multiple routes and each handler has a significant amount of code, it is not desirable for supervisors.

Next we further optimize the structure.

The controller layer separation

We also separate the business logic corresponding to the route.

The new controller/home. Js

Create a controller folder, add a home.js file, and extract the business logic code from router.js.

  module.exports = {
    index: async(ctx, next) => {
      ctx.response.body = `<h1>index page</h1>`
    },
    home: async(ctx, next) => {
      console.log(ctx.request.query)
      console.log(ctx.request.querystring)
      ctx.response.body = '<h1>HOME page</h1>'
    },
    homeParams: async(ctx, next) => {
      console.log(ctx.params)
      ctx.response.body = '<h1>HOME page /:id/:name</h1>'
    },
    login: async(ctx, next) => {
      ctx.response.body =
        
      




}, register: async(ctx, next) => { let { name, password } = ctx.request.body if (name == 'ikcamp' && password == '123456') { ctx.response.body = ` Hello,${name}! ` } else { ctx.response.body = 'Account information error'}}}Copy the code

Example Modify the router.js route

Controler/Home: controler/home:

  const router = require('koa-router') ()const HomeController = require('./controller/home')
  module.exports = (app) = > {
    router.get( '/', HomeController.index )
    
    router.get('/home', HomeController.home)
    
    router.get('/home/:id/:name', HomeController.homeParams)
    
    router.get('/user', HomeController.login)
    
    router.post('/user/register', HomeController.register)
    
    app.use(router.routes())
      .use(router.allowedMethods())
  }
Copy the code

In this way, the processing logic of each route is separated into a separate file under the controller for later maintenance.

The current code structure has been relatively clear, suitable for node as the middle layer, the transit layer of the project. If you want to use Node as the real back-end to operate the database, it is suggested to separate a layer of Service to handle the data level interaction, such as calling model to process the database, calling third-party interfaces, etc., while controller only does some simple parameter processing.

The service layer separation

This separation, which is not necessary, can be increased depending on the project, or all business logic can be placed in the Controller.

The new service/home. Js

Create a service folder and add a home.js file to that folder to extract some code from controller/home.js:

  module.exports = {
    register: async(name, pwd) => {
      let data 
      if (name == 'ikcamp' && pwd == '123456') {
        data = ` Hello,${name}! `
      } else {
        data = 'Account information error'
      }
      return data
    }
  }
Copy the code

Modify the controller/home. Js

// Import the service file
const HomeService = require('.. /service/home')
module.exports = {
  / /... Omit the above code
  // Override the register method
  register: async(ctx, next) => {
    let {
      name,
      password
    } = ctx.request.body
    let data = await HomeService.register(name, password)
    ctx.response.body = data
  }
}
Copy the code

Refactoring to complete

In the next section we will introduce the views layer and use third-party middleware to set up static resource directories. The addition of some front-end source code will bring our use cases to life, so look forward to it.

Next: View Nunjucks – Koa default supported template engine

~~~~~iKcamp | Construct Node.js based on Koa2 ☞ HTTP request

Translation project Master:

1. Dry goods | Everyone is the Master of translation project

2. IKcamp produces a total of 5 chapters and 16 sections of wechat mini program teaching (video included)


In 2019, iKcamp’s original new book Koa and Node.js Development Actual Combat has been sold on JD.com, Tmall, Amazon and Dangdang!