目录

重构及封装

重构及封装

重构笔记

  • 关键代码
  1. app.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)
  1. books.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

}
  1. router/index.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();
  1. router/utils.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

@url = http://localhost:4000

###

GET {
{url}}/blogs HTTP/1.1

Content-Type: application/json

{

"name":"巴拉巴拉"

}

###

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