当前位置:网站首页>Koa_ mySQL_ Integration of TS

Koa_ mySQL_ Integration of TS

2022-06-26 08:31:00 BloggerM

Koa_mySQL_Ts Integration of

  • Desktop new folder ts_mysql_koa

  • Initialize project :npm init -y

     Insert picture description here

  • Install some required third-party modules :npm i koa koa-router koa-bodyparser typescript mysql2

     Insert picture description here

  • stay package.json Configuration script

    {
          
      "name": "ts_mysql_koa",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
          
        "start": "ts-node-dev ./src/app.ts"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
          
        "koa": "^2.13.4",
        "koa-bodyparser": "^4.3.0",
        "koa-router": "^10.1.1",
        "mysql2": "^2.3.3",
        "ts-node-dev": "^2.0.0",
        "typescript": "^4.7.4"
      }
    }
    
  • Create a new folder in the root directory src, In the folder src Next, create a new folder app.ts As an entry file .

  • Build the directory structure of the project

     Insert picture description here

  • Start by opening Navicat Premium Database development tools , New database mall

    use mall;
    
    CREATE TABLE `user` (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(20),
    `password` VARCHAR(20),
    nickName VARCHAR(20),
    age INT,
    birthday TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    
    INSERT INTO `user` SET username = 'admin',password = '123456',nickname = ' Zhang San ',age = 18;
    INSERT INTO `user` SET username = 'lisi',password = '123456',nickname = ' Li Si ',age = 18;
    INSERT INTO `user` SET username = 'wangwu',password = '123456',nickname = ' Wang Wu ',age = 18;
    INSERT INTO `user` SET username = 'zhaoliu',password = '123456',nickname = ' Zhao Liu ',age = 18;
    
    SELECT * FROM `user`;
    
  • stay config New under folder db.ts Folder

    export default {
          
        host:'localhost',
        port:3306,
        user:'root',
        password:'123456',
        database:'mall'
    }
    
  • stay util Create a new file under the folder index.ts( Encapsulate database operation statements )

    import {
          createConnection} from "mysql2";
    import config from '../config/db'
    
    //  Get database connection 
    const connection = createConnection(config)
    
    export default class DBUtil {
          
        //  Encapsulate common database operation statements 
        static query(sql:string,params?:any|any[]|{
          [param:string]:any}):Promise<any>{
          
            //  adopt Promise Returns the result of the database operation 
            return new Promise<unknown>((resolve,reject)=>{
          
                //  Execute via database connection sql sentence 
                connection.query(sql,params,(err,result,fields)=>{
          
                    //  Judge sql Is there any error in execution 
                    if(err){
          
                        //  Failure 
                        reject(err)
                    }else {
          
                        //  success 
                        resolve(result
    
                        )
                    }
                })
            })
        }
    }
    
  • stay router New under the folder user.ts

    import * as Router from 'koa-router'
    
    import UserService from '../service/user'
    
    const userRouter = new Router({
          prefix:'/user'})
    
    const {
          queryAll,count,queryOne,del,save,edit} = new UserService()
    /** *  Query all  */
    userRouter.get('/',queryAll)
    
    /** *  Query quantity  */
    userRouter.get('/count',count)
    
    /** *  according to id Inquire about  */
    userRouter.get('/:id',queryOne)
    
    /** *  according to id Delete  */
    userRouter.delete('/:id',del)
    
    /** *  add to  */
    userRouter.post('/',save)
    
    /** *  modify  */
    userRouter.patch('/:id',edit)
    
    export default userRouter
    
  • stay service New under the folder user.ts

    import UserController from '../controller/user'
    
    const {
          queryAll,getCount,queryOne,del,save,edit} = new UserController()
    
    export default class UserService{
          
        /** *  Query all  * @param ctx */
        async queryAll(ctx):Promise<void>{
          
            const {
          page}=ctx.query
            let currentPage = 1
            if(page && page !='undefined') {
          
                currentPage = (page - 1) * 10
            }
            const res = await queryAll([currentPage,10])
            ctx.body = res
        }
    
        /** *  Number  * @param ctx */
        async count(ctx):Promise<void>{
          
            const [count] = await getCount()
            ctx.body = count
        }
    
        /** *  according to id Inquire about  * @param ctx */
        async queryOne(ctx):Promise<void>{
          
            const {
          id} = ctx.params
            const [res] = await queryOne(id)
            ctx.body = res
        }
    
        /** *  according to id Delete  * @param ctx */
        async del(ctx):Promise<void>{
          
            const {
          id} = ctx.params
            const {
          affectedRows} = await del([id])
            ctx.body = affectedRows?' Delete successful ':' Delete failed '
        }
    
        /** *  add to  * @param ctx */
        async save(ctx):Promise<void>{
          
            const body = ctx.request.body
            const {
          insertId} = await save(body)
            ctx.body = insertId?' Add success ':' Add failure '
        }
    
        /** *  modify  * @param ctx */
        async edit(ctx):Promise<void>{
          
            const body = ctx.request.body
            const {
          id} = ctx.params
            const {
          affectedRows} = await edit([body,id])
            ctx.body = affectedRows?' Modification successful ':' Modification failed '
        }
    }
    
  • stay controller New under the folder user.ts

    import DBUtil from '../util'
    
    export default class UserController {
          
        /** *  Query all  * @param params */
        queryAll(params:any){
          
            return DBUtil.query('select * from user limit ?,?',params)
        }
        getCount(){
          
            return DBUtil.query('select count(*) as count from user')
        }
    
        /** *  according to id Inquire about  * @param params */
        queryOne(params:any){
          
            return DBUtil.query('select * from user where id=?',params)
        }
    
        /** *  according to id Delete  * @param params */
        del(params:any){
          
            return DBUtil.query('delete from user where id=?',params)
        }
    
        /** *  add to  * @param params */
        save(params:any){
          
            return DBUtil.query('insert into user set ?',params)
        }
    
        /** *  modify  * @param params */
        edit(params:any){
          
            return DBUtil.query('update user set ? where id=?',params)
        }
    }
    
  • According to the Postman Interface test tools test one by one , Unmistakable

原网站

版权声明
本文为[BloggerM]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260826206277.html