基於 Koa.js 的 Node.js MVC 框架

0. 簡介

  • 項目名:基於 Koa.js 的 Node.js MVC 框架。
  • 倉庫地址:github.com/zhaotoday/k…
  • 負責人:趙金添@zhaotoday
  • 特別說明:本項目參考了 Egg.js 框架及 iKcamp 分享的 Koa 視頻教程。

1. 運行

1.1. Node 版本

Koa2 使用了 async/await 等新語法,請保證 Node 版本在 7.6 及以上。css

1.2. 命令

# 安裝依賴
$ npm install

# JS 代碼校驗
$ npm run eslintfix
$ npm run eslint

# 開發
$ npm run dev

# 啓動項目
$ npm start

# 中止項目
$ npm run stop
複製代碼

2. 規範

2.1. 目錄結構

├─ src                     源碼
│  ├─ app                  業務代碼
│  │  ├─ controllers       控制器:用於解析用戶輸入,處理後返回相應的結果
│  │  ├─ models            模型  :用於定義數據模型
│  │  ├─ services          服務  :用於編寫業務邏輯層,好比鏈接數據庫,調用第三方接口等
│  │  └─ views             視圖  :用於放置模板文件,返回客戶端的視圖層
│  │
│  ├─ core                 核心代碼
│  │  ├─ controller.js     控制器基類
│  │  ├─ model.js          模型基類
│  │  └─ service.js        服務基類
│  │
│  ├─ middlewares          中間件
│  ├─ public               靜態資源
│  ├─ router               URL 路由
│  ├─ utils                工具庫
│  └─ index.js             入口:用於自定義啓動時的初始化工做,好比啓動 https,調用中間件、路由等
│  
├─ .eslintrc               eslint 配置文件
├─ nodemon.json            nodemon 配置文件
├─ package.json            npm 配置文件
├─ processes.json          pm2 配置文件
複製代碼

2.2. 自定義掛載對象

爲了提升開發效率,這裏人爲的將一些自定義對象掛載到 app 下,用 $ 前綴命名,與 Koa.js 內置對象作區分。html

  • app.$helpers:輔助函數
  • app.$model:公用模型對象
  • app.$Service:服務基類
  • app.$Controller:控制器基類
  • app.$models:模型集合
  • app.$services:服務集合
  • app.$controllers:控制器集合

2.3. 示例

2.3.1. 模型

src/app/models/articles.js前端

module.exports = app => {
  const {ID, SHORT_RELATED_ID, NAME, TITLE, SUBTITLE, DESCRIPTION, CONTENT, PICTURES, ORDER} = app.$model.columns

  return app.$model.define('articles', {
    id: ID,
    category_id: SHORT_RELATED_ID,
    author: NAME,
    title: TITLE,
    subtitle: SUBTITLE,
    description: DESCRIPTION,
    content: CONTENT,
    pictures: PICTURES,
    order: ORDER
  })
}
複製代碼

2.3.2. 服務

src/app/services/articles.jsnode

module.exports = app => {
  return class extends app.$Service {
    constructor () {
      super()

      this.model = app.$models.articles
    }
  }
}
複製代碼

2.3.3. 控制器

src/app/controllers/articles.jsreact

module.exports = app => {
  const service = app.$services.articles

  return class extends app.$Controller {
    async index (ctx, next) {
      await ctx.render('articles', {
        items: await service.find({offset: 0, limit: 10})
      })
    }
  }
}
複製代碼

2.3.4. 視圖

src/app/views/articles.ejsnginx

<%- JSON.stringify(items) %>
複製代碼

2.3.5. API

src/app/controllers/apis/v1/articles.jsgit

module.exports = app => {
  const service = app.$services.articles

  return class extends app.$Controller {
    async index (ctx, next) {
      ctx.response.body = ctx.send({
        status: 200,
        data: await service.find({offset: 0, limit: 10})
      })
    }
  }
}
複製代碼

2.3.6. 路由

src/router/routes/articles.jsgithub

module.exports = (app, router) => {
  router.get('/articles', app.$controllers.articles.index)
}
複製代碼

3. 參考

3.1. 文檔

3.2. 文章

3.3. 安全

相關文章
相關標籤/搜索