koa 2 Restful APIを実現

5723 ワード

koaジェネレータのインストール
npm install koa-generator -g

プロジェクトを生成して依存関係をインストール
koa2 test && cd test && npm install

うんてん
npm run dev

ブラウザを開くhttp://localhost:3000 初期インタフェースが見えます
ルーティングの作成
app.js
const api = require('./routes/api')
app.use(api.routes(), api.allowedMethods())

routes/api/index.js
const router = require('koa-router')()
const controller = require('../../controller/api')

router.prefix('/api')

router.get('/', async (ctx, next) => {
  ctx.body = 'api'
})

router.get('/find', controller.find)

router.post('/insert', controller.insert)

router.delete('/delete', controller.del)

router.put('/update', controller.update)

module.exports = router


コントローラの作成(controller)
controller/api/users.js
const service = require('../../service/api/users')

class usersController {
  static async find(ctx) {
    ctx.body = await service.findAll()
  }
  static async insert(ctx) {
    ctx.body = await service.insert(ctx.request.body)
  }
  static async delete(ctx) {
    ctx.body = await service.delete(ctx.request.body)
  }
  static async update(ctx) {
    ctx.body = await service.update(ctx.request.body)
  }
}

module.exports = usersController

ビジネスロジックの作成(service)
service/api/users.js
const userModel = require('../../lib/users.js')

class usersService {
  static async findAll() {
    return await userModel.findAllData()
  }
  static async insert(data) {
    let v = [data.name, data.pwd, data.sex, data.role, new Date()]
    return await userModel.insertData(v)
  }
  static async delete(data) {
    return await userModel.deleteData(data.name)
  }
  static async update(data) {
    let v = [data.age, data.name]
    return await userModel.updateData(v)
  }
}

module.exports = usersService

mysqlプラグインのインストール
npm i mysql --save

userテーブル構造の作成
CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `user_pwd` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `user_sex` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `user_age` int(3) DEFAULT NULL,
  `user_city` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `user_tel` int(13) DEFAULT NULL,
  `user_email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `user_avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `user_role` int(2) NOT NULL,
  `user_createdate` date NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;

デフォルト設定の作成
config/default.js
const config = {
  //      
  database: {
    DATABASE: 'noal',
    USERNAME: 'noal',
    PASSWORD: '123456',
    PORT: '3306',
    HOST: 'localhost'
  }
}

module.exports = config

データベース接続コードの作成
lib/mysql.js
const mysql = require('mysql')
const config = require('../config/default.js')

const pool = mysql.createPool({
  host        : config.database.HOST,
  user        : config.database.USERNAME,
  password    : config.database.PASSWORD,
  database    : config.database.DATABASE,
  port        : config.database.PORT,
  dateStrings : true
})

let query = ( sql, values ) => {
  return new Promise(( resolve, reject ) => {
    pool.getConnection( (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


増削除改査sqlを作成する
lib/users.js
const query = require('./mysql')

class usersSql {
  findAllData() {
    let  _sql = `SELECT * FROM user`
    return query(_sql)
  }
  insertData(v) {
    let _sql = `insert into user set user_name=?,
    user_pwd=?,user_sex=?,user_role=?,user_createdate=?;`
    // let  _sql = `insert into user set user_name = "${v.name}";`
    return query(_sql, v)
  }
  deleteData(name) {
    let _sql = `delete from user where user_name="${name}";`
    return query(_sql)
  }
  updateData(data) {
    let _sql = `update user set user_age=? where user_name=?;`
    return query(_sql, data)
  }
}

module.exports = new usersSql

リクエストインタフェース
koa2实现Restful API_第1张图片findfindkoa2实现Restful API_第2张图片githubソースアドレスhttps://github.com/jwnoal/koa2-mynote/tree/restfulapi