next + koa + mongodb to build deployment from (a)

Foreword

Read many articles to write server-side rendering (next.js), but found the service side rendering Finder are some of the more simple, or less systematic example, if you do a presentation or demo is still possible, but in practice not conducive to the division of labor on the application, deployed on the line. Obviously you can do large-scale projects but do not know how to apply, so take these pain points and doubts, I decided to make their own set of next + koa + mongodb framework can be applied to the project application-level project (this project is still updating), the project is still continued optimization, we can hope a lot of pointing.

Man of few words said on the map first began to introduce the idea of ​​planning and projects under

Project Introduction

This is the project's home page, we should be able to see it, it is a parody of the Nuggets personal blog project. Contains the basic login, registration, write articles, to show the article. . . Follow-up will continue to add new features. The goal is posted on-line, continuous iteration, mature and eventually made a complete project.

Project structure

Like traditional ssr project, divided View layer, and sever layer, unfamiliar next.js, and koa.js can go to the brain make it next document && KOA documents , view layer at the back would simply say, let's focus talk about building server layer, sever layer is divided into apps.js (entry file app.js obsolete), controller (interface definition, rendering the page configuration), middleware (middleware), router (routing), token (Login token defined when registering)

  • Entry file apps.js
const Koa = require('koa')
const next = require('next')
const koaRoute = require('./router')
const bodyParser = require('koa-bodyparser');
const middleware = require('./middleware')
const cors = require('koa2-cors');

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()


app.prepare()
  .then(() => {
    const server = new Koa()
     //注入中间件
     middleware(server)
     server.use(bodyParser())
    //注入路由
    koaRoute(server,app,handle)
    server.listen(port, () => {
      console.log(`> Ready on http://localhost:${port}`)
    })
  })
复制代码

1.middleware

apps.js entry file is relatively simple, because the main logic package into the assembly, start talking middleware

const bodyParser = require('koa-bodyparser');
const logger = () =>  {
    return async (ctx, next) => {
      const start = Date.now()
      bodyParser()
  
      await next()
  
      const responseTime = (Date.now() - start)
      console.log(`响应时间为: ${responseTime / 1000}s`)
    }
  }
  
  module.exports = (app) => {
    app.use(logger())
  }
复制代码

If you have read koa document will find that regardless of the route and the use of plug-ins, we need new Koa () and then use later to call, only use this method a response time, it could be used more among the middle, if introduced on a is introduced at the inlet will be a more complicated, so the general method of packaging, can continue to add, at the inlet only once it is introduced.

2. controller

koa controller which is mainly in the routing manager, into the interface management (API) and routing management view (view) and database management (db.js), and the file entry (index.js).

api in the getListInfor.js:

const DB = require('../db')
const loginInfor = (app) =>{
    return async (ctx, next) => {
       await DB.insert(ctx.request.body).then(res =>{
            ctx.response.body = {
               infor:'ok'
            }
       })
       
    }
}
module.exports =  loginInfor
复制代码

in view of home.js

const home = (app) =>{
    return async (ctx, next) => {
        await app.render(ctx.req, ctx.res, '/home', ctx.query)
        ctx.respond = false
    }
}
module.exports = home
复制代码

api.js

const Monk = require('monk')
const url = 'mongodb://localhost:27017/home'; // Connection URL
const db  =  Monk(url)
const dbName = 'col'
const collection = db.get(dbName)

module.exports = collection

//本地用mongdb搭建的数据库,调用方法用的monk插件,不了解的可以去github搜索 
复制代码

index.js:

//VIEW
const index = require('./view/index')
const home = require('./view/home')
const editText = require('./view/editText')
const essay = require('./view/essay')
const myself = require('./view/myself')

//API
const getListInfor = require('./api/getListInfor')
const loginInfor   = require('./api/loginInfor')
const POST = 'post'
const GET  = 'get'


module.exports = {
    view:{// 不需要请求方式
        index,
        home,
        editText,
        essay,
        myself,
    },
    api:{
        getListInfor:{
            method:GET,
            getListInfor
        },
        loginInfor:{
            method:POST,
            loginInfor
        }
    }

  }
复制代码

3.router

const router = require('./node_modules/koa-router')()
const Controller = require('../controller')

const koaRoute = (app,handle) =>{   //把view层和api层挂载到router
        // view 
        const {view,api} = Controller  
        for(item in view){
            let _name = null;
            let _moudle = null
            if(item == 'index'){
                _name = '/';
                _moudle = view['index']
            }else{
                _name = '/' + item;
                _moudle = view[item]
            }
            router.get(_name,_moudle(app))
        }
        //api 
        for(item in api){
           let  _method = api[item].method
           let _name    = '/' + item;
           let _moudle  = api[item][item]
          router[_method](_name,_moudle(app))
      }
        
          router.get('*', async ctx => {
            await handle(ctx.req, ctx.res)
            ctx.respond = false
          })
      
          return router.routes()  //启动路由
      }

module.exports = (server,app,handle) =>{
    server.use(koaRoute(app,handle))
}
复制代码

This time you can look at what apps.js is how the introduction of:

const app = next({ dev })
const handle = app.getRequestHandler()
const koaRoute = require('./router')


app.prepare()
  .then(() => {
    const server = new Koa()
    //注入路由
    koaRoute(server,app,handle)  // 相当于koa里面app.use(router.routes()) 启动路由......
复制代码

To be continued. . .

Reproduced in: https: //juejin.im/post/5cc7a8aaf265da03a74400a9

Guess you like

Origin blog.csdn.net/weixin_33727510/article/details/91424077