wangjiahui

koa2 框架结构

  • controllers 项目控制器目录接受请求处理逻辑
  • DataBase 保存数据库封装的CRUD操作方法
  • models文件夹 对应的数据库表结构
  • config文件夹 项目路由文件夹
  • app.js 入口文件

以上文件夹没有固定名称 但是项目当中都会以类似结构进行

avatar

如上图所示基本的项目结构就包含这些,现在了解了koa的一个项目结构,下一步就可以进行操作数据库了,这里推荐mongodb,为啥呢?mongodb的语法与js类似,学习成本低

mongodb官方文档: https://www.mongodb.com/what-is-mongodb
新手的话推荐用可视化工具 robot 3T : https://robomongo.org

控制器 (controllers/user.js)

用于接收用户模块的接口请求,如注册、更新、删除、获取用于列表、搜索用户等相关请求,以下是注册请求的举例。主要是通过koa-router实现路由转发请求到该接口,然后使用封装的dbHelper对mongodb进行操作(当然这里我直接使用了mongose的api进行数据库的操作了,比较low)。

model层:表结构的定义,model/user.js

mongoose的语法,先定义一个schema,再导出一个model。
mongodb官方文档 :http://www.nodeclass.com/api/mongoose.html


const fs = require(\'fs\')
const path = require(\'path\')
const mongoose = require(\'mongoose\')

const db = \'mongodb://localhost/test\'

/**
 * mongoose连接数据库
 * @type {[type]}
 */
mongoose.Promise = require(\'bluebird\')
mongoose.connect(db)

/**
 * 获取数据库表对应的js对象所在的路径
 * @type {[type]}
 */
const models_path = path.join(__dirname, \'/app/models\')


/**
 * 已递归的形式,读取models文件夹下的js模型文件,并require
 * @param  {[type]} modelPath [description]
 * @return {[type]}           [description]
 */
var walk = function(modelPath) {
  fs
    .readdirSync(modelPath)
    .forEach(function(file) {
      var filePath = path.join(modelPath, \'/\' + file)
      var stat = fs.statSync(filePath)

      if (stat.isFile()) {
        if (/(.*)\.(js|coffee)/.test(file)) {
          require(filePath)
        }
      }
      else if (stat.isDirectory()) {
        walk(filePath)
      }
    })
}
walk(models_path)

require(\'babel-register\')
const Koa = require(\'koa\')
const logger = require(\'koa-logger\')
const session = require(\'koa-session\')
const bodyParser = require(\'koa-bodyparser\')
const app = new Koa()

app.keys = [\'zhangivon\']
app.use(logger())
app.use(session(app))
app.use(bodyParser())


/**
 * 使用路由转发请求
 * @type {[type]}
 */
const router = require(\'./config/router\')()

app
  .use(router.routes())
  .use(router.allowedMethods());



app.listen(1234)
console.log(\'app started at port 1234...\');

以上是github上的一段代码,可以看见的事,虽然安装koa 并不会像express一样直接生成整个项目结构,但是,当我们了解了koa框架以后,其实本质上来讲和express整体结构类似。都遵循传统node的commonjs规范

分类:

技术点:

相关文章:

  • 2021-04-08
  • 2021-11-27
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2021-08-16
猜你喜欢
  • 2021-12-08
  • 2021-12-27
  • 2021-07-23
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案