zoukankan      html  css  js  c++  java
  • 7 更良好的项目目录结构

    1. 在上面的增删改查例子中, 我们将所有路由和控制器都写在了index.js中, 等到我们的代码量越来越大,这样显然是不合理的。所以, 我们应该构建良好的项目结构

     首先, 在根目录下创建app文件夹, 将index.js放入该目录下

     在app文件夹下, 创建控制器目录controllers、路由目录routes

     

    2. 为了功能独立,路由只负责路由的事,中间件则负责功能和模块,我们需要将我们写的代码分离出来

     根据接口功能的不同, 我们将项目暂时划分为首页和用户

     

     

    3. home模块

     controllers > home.js

    class HomeCtl{
      index(ctx) {
        ctx.body='<h1>这是主页</h1>'
      }
    }
    
    module.exports = new HomeCtl()

      routes > home.js

    const Router = require('koa-router')
    const router = new Router()
    const { index } = require('../controllers/home')
    
    router.get('/', index)
    
    module.exports = router

    4. 用户模块

      controllers > users.js

    const db = [
      {"name" : "zhanghao"}
    ]
    
    class UserCtl{
      //获取用户列表
      find(ctx) {
        ctx.body = db
      }
    
      //增加用户
      create(ctx) {
        ctx.verifyParams({
          name: {type : 'string', required: true},
          age: {type: 'number', required: false}
        })
        db.push(ctx.request.body)
        ctx.body = ctx.request.body
      }
    
      //获取特定用户
      findById(ctx) {
        if(ctx.params.id * 1 < 0 ) {
          ctx.throw(404, '这个用户太小了, 找不到')
        }
        ctx.body = db[ctx.params.id * 1]
      }
    
      //修改用户
      update(ctx){
        db[ctx.params.id] = ctx.request.body
        ctx.body = ctx.request.body
      }
    
      //删除用户
      deleted(ctx) {
        db.splice(ctx.params.id, 1)
        ctx.status = 204
      }
    }
    
    module.exports = new UserCtl()

     routes > users

    const Router = require('koa-router')
    const router = new Router({prefix: '/users'})
    const { find , findById, create, update, deleted } = require('../controllers/users')
    
    router.get('/', find)
    
    router.post('/', create)
    
    router.get('/:id', findById)
    
    router.delete('/:id', deleted)
    
    router.put('/:id', update)
    
    module.exports = router

     

  • 相关阅读:
    echarts雷达图点击事件 包含(2.x,3.85,4.02)测试
    字体图标制作
    通过php动态传数据到highcharts
    smartgit试用到期不用序列号怎么继续使用
    项目的ip地址更改,用git从远程提取代码出现错误,提示为 network error connection timed out
    OC学习4——OC新特性之块(Block)
    OC学习3——C语言特性之指针
    OC学习2——C语言特性之函数
    OC学习1——基本数据类型
    JVM 内存的那些事
  • 原文地址:https://www.cnblogs.com/zhanghaoblog/p/11710830.html
Copyright © 2011-2022 走看看