koa搭建接口服務

1.項目規劃圖node

 2.路由器代碼mysql

const Router = require('koa-router')

const router = new Router({
  prefix: '/api'
})
const allRouter = new Router()
const gameRouter = new Router()

// 處理模塊
const gameClick = require('../middleware/game')
const demoClick = require('../middleware/demo')


//指定路由,從上到下識別
//localhost:3000/api/game/test
gameRouter
  .get('/test', gameClick.test_get)
  .post('/test', gameClick.test_post)
  .put('/test/:id', gameClick.test_put)
  .del('/test/:id', gameClick.test_delete)

// 全局路由
allRouter
  .get('*', demoClick.getAll)
  .post('*', demoClick.postAll)
  .put('*', demoClick.postAll)
  .del('*', demoClick.postAll)

router.use('/game', gameRouter.routes(), gameRouter.allowedMethods())
router.use('*', allRouter.routes(), allRouter.allowedMethods())

module.exports = router.routes()

  

3.中間層代碼ios

const gameAxios = require('../controllers/game')
const CommonSend = require('../api/send')
const {
  query
} = require('../api/sqlServer.js')

// 中間模塊
class CommonClick {

  // 測試列表
  static async test_get(ctx) {
    let data = {
      page: ctx.query.page || 1
    }
    await gameAxios.test_get(data).then((res) => {
      ctx.body = CommonSend.list(res)
    }).catch((err) => {
      ctx.body = CommonSend.err('操做失敗')
    })
  }

  // 添加測試
  static async test_post(ctx) {
    let name = ctx.request.body.name || ''
    let password = ctx.request.body.password || ''
    let data = {
      name: name,
      password: password
    }
    await gameAxios.test_post(data).then((res) => {
      ctx.body = CommonSend.success('操做成功')
    }).catch((err) => {
      ctx.body = CommonSend.err('操做失敗')
    })
  }

  // 修改測試
  static async test_put(ctx) {
    let password = ctx.request.body.password
    let id = ctx.request.url.split('/')[4]
    let data = {
      id: id,
      password: password
    }
    await gameAxios.test_put(data).then((res) => {
      ctx.body = CommonSend.success(res)
    }).catch((err) => {
      ctx.body = CommonSend.err('操做失敗')
    })
  }

  // 刪除測試
  static async test_delete(ctx) {
    let id = ctx.request.url.split('/')[4]
    if (id !== 'undefind') {
      await gameAxios.test_delete(id).then((res) => {
        ctx.body = send.success(res)
      }).catch((err) => {
        ctx.body = send.err('操做失敗')
      })
    }

  }

}

module.exports = CommonClick

  

4.控制器代碼sql

const sql = require('../api/common.js')

// 公共模塊
class CommonCtrl {
  // 測試列表
  static test_get(data) {
    let page = data.page
    return sql.select('name', '*', '', page)

  }

  // 添加測試
  static test_post(data) {
    return sql.insert('name', data)
  }

  // 修改測試
  static test_put(data, id) {
    return sql.update('name', data, id)
  }

  // 刪除測試
  static test_delete(id) {
    return sql.deletes('name', id)
  }

}

module.exports = CommonCtrl

  

5.鏈接數據庫數據庫

const mysql = require('mysql')

let apiStatus = false //true爲本地數據庫,false爲阿里雲數據庫

let pool

if (apiStatus) {
  pool = mysql.createPool({
    host: 'localhost', // 數據庫地址
    user: 'root', // 數據庫用戶
    password: 'root', // 數據庫密碼
    database: 'node_api' // 選中數據庫
  })
}

const query = function (sql, values) {
  return new Promise((resolve, reject) => {

    pool.getConnection(function (err, connection) {
      if (err) {
        reject(err)
      } else {
        connection.query(sql, values, (err, rows) => {
          if (err) {
            reject(err)
          } else {
            resolve(rows)
          }
          connection.release()
        })
      }
    })
  })
}

module.exports = {
  query
}

  

6.封裝增刪改查api

const {
  query
} = require('./sqlServer')

let $sql

// 公共模塊
class CommonSql {

  //添加
  static insert($table, array, props) {
    let keys = '',
      values = ''
    for (let key in array) {
      keys += ',' + key
      values += ',' + array[key]
    }
    let $keys = keys.substr(1)
    let $values = values.substr(1)
    $sql = `insert into ${$table}(${$keys}) values(${$values})`;
    return query($sql)
  }

  //獲取
  static async select($table, $what, array, $page) {
    let keys = ''
    for (let key in array) {
      keys += ' and ' + key + '=' + array[key]
    }
    let $keys = keys.substr(5)

    let pageNum = 20
    let startNum = ($page - 1) * pageNum
    let endNum = $page * pageNum

    if (array) {
      $sql = `select sql_calc_found_rows ${$what} from ${$table} where ${$keys} ORDER BY id desc LIMIT ${startNum},${endNum}`
    } else {
      $sql = `select sql_calc_found_rows ${$what} from ${$table} ORDER BY id desc LIMIT ${startNum},${endNum}`;
    }

    let list = await query($sql)
    let number = await query(`SELECT FOUND_ROWS() as total;`)
    let date = {
      data: list,
      meta: {
        pagination: {
          total: number[0].total,
          page_count: 20,
          per_page: Math.ceil(number[0].total / 20),
          current_page: parseInt($page)
        }
      }
    }

    return date


  }

  //修改
  static update($table, array, $id) {
    let keys = ''
    for (let key in array) {
      keys += ',' + key + '=' + array[key]
    }
    let $keys = keys.substr(1)
    $sql = `update ${$table} set ${$keys} where id = ${$id}`
    return query($sql)
  }

  //刪除
  static deletes($table, $id) {
    $sql = `delete  from ${$table} where id =  ${$id}`
    return query($sql)
  }

}

module.exports = CommonSql
相關文章
相關標籤/搜索