当前位置: 首页 > article >正文

重构及封装

## 重构笔记

- 关键代码

1. app.js

```js

import koa from "koa"

import router from "koa-router"

import bodyparser from "koa-bodyparser"

import { route } from "./router/index.js"

const app = new koa()

const Router = new router()

app.use(bodyparser())

// 找到并遍历所有指定路径下的js文件

app.use(route)

app.listen(4000)

```

2. books.js

```js

let list = async(ctx,next) =>{

    console.log('图书列表');

    ctx.body = '图书列表'

}

let list_Id = async(ctx,next) =>{

    let Id = ctx.params.Id

    ctx.body = '单个图书'

}

let list_add = async(ctx,next) =>{

    ctx.body = '新增图书'

}

let list_update = async(ctx,next) =>{

    let Id = ctx.params.Id

    ctx.body = '修改图书'

}

let list_del = async(ctx,next) =>{

    ctx.body = '删除'

}

export const obj = {

    'get /books' : list,

    'get /books/:id' :list_Id,

    'post /books/' : list_add,

    'put /books/:id' : list_update,

    'delete /books' : list_del

}

```

3. router/index.js

```js

import Router from "koa-router"

import path from "path"

import {FAllCon,Reg} from "./utils.js"

let router =new Router()

/*

    1. 注册路由【通过两个函数】【把 router 传进去】

    2. 使用app.use(Router.routes())

*/

// 传路径

let dir = '../Controller'


 

// 找到所有的控制器文件

let controllers = FAllCon(dir)


 

// 注册路由

Reg(router,controllers)




 

/*

1. 具名导出

    export let abc      // import {abc} from ''

2. deefault {} 全场只能出现一个 default

    export default {}   // import x from ''

*/

export let route = router.routes();

```

4. router/utils.js

```js

import { log } from 'console';

import fs from 'fs'

import path from "path"

// 找到所有的控制器文件

function findAllControllers(ConDir){

    // 使用绝对路径

    const ab = `F:/123/28/Controller`

    let aaa = fs.readdirSync(ab)

    console.log(aaa);

   

    if (fs.existsSync(ab)) {

        let allFile = fs.readdirSync(ab)

        let allConFiles = allFile.filter(x=>x.endsWith('.js')).map(x=>`file:///${ab}/${x}`)

        return allConFiles

    }

}

// 注册路由

function regRouter(router,controllers){

    // 遍历所有的控制器,动态导入每个控制器模块

    controllers.forEach(async file => {

        // 动态导入模块

        let {obj} = await import(file)

        // 遍历对象

        for (const key in obj) {

            let x = key.split(' ')

            console.log(x);

            let [keyMethod,keyPath] = key.split(' ')

            let keyFn = obj[key]

            console.log(keyMethod);

           

            if (keyMethod === 'get') {

                router.get(keyPath,keyFn)

            }

            if (keyMethod === 'post') {

                router.post(keyPath,keyFn)

            }

            if (keyMethod === 'delete') {

                router.delete(keyPath,keyFn)

            }

            if (keyMethod === 'put') {

                router.put(keyPath,keyFn)

            }

        }

    });

}

export const FAllCon = findAllControllers

export const Reg = regRouter

```

5.

```h

    @url = http://localhost:4000

    ###

    GET {{url}}/blogs HTTP/1.1

    Content-Type: application/json

    {

        "name":"巴拉巴拉"

    }

    ###

    get {{url}}/blogs/:id HTTP/1.1

```


http://www.kler.cn/a/581340.html

相关文章:

  • 2025-3-11 leetcode刷题情况(贪心算法--区间问题)
  • 计算机视觉算法实战——昆虫识别检测(主页有源码)
  • CSS小玩意儿:目录
  • 树莓派4B使用Ubuntu20.04连接不上热点
  • conda创建Python虚拟环境的原理
  • 基于 Vue 的Deepseek流式加载对话Demo
  • 基于python下载ERA5小时尺度和月尺度的数据
  • 【反无人机数据集】【目标检测】基于深度学习和距离分析的无人机检测图像处理技术应用
  • 基于MATLAB的冰块变化仿真
  • XTDrone调试报错问题集锦
  • 动态规划详解(二):从暴力递归到动态规划的完整优化之路
  • NLP常见任务专题介绍(2)-多项选择任务(MultipleChoice)训练与推理模板
  • SpringBoot开发——整合SpringReport开源报表工具
  • Git的命令学习——适用小白版
  • Android实现Socket通信
  • Chrome 扩展开发 API实战:Bookmarks(二)
  • Python高级之操作Mysql
  • 华为OD机试 - 平均像素值-贪心算法(Java 2024 E卷 100分)
  • 【区块链+ 医疗健康】基于区块链和AI 技术的儿童近视防控大数据平台 | FISCO BCOS 应用案例
  • iTextSharp-PDF批量导出