koa2 框架結構
- controllers 項目控制器目錄接受請求處理邏輯
- DataBase 保存數據庫封裝的CRUD操作方法
- models文件夾 對應的數據庫表結構
- config文件夾 項目路由文件夾
- app.js 入口文件
以上文件夾沒有固定名稱 但是項目當中都會以類似結構進行
如上圖所示基本的項目結構就包含這些,現在了解了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...');