I recently practiced koa, there are two needs.

  • The content returned by the interface remains uniform
  • I don't want to process ctx.body for the interface code, I want to return when I get the result, and throw when there is an error.

So I wrote a middleware, the code is like this.

const ApiRouter = () => async (ctx, next) => {
    try {
        const data = await next()
        ctx.body = {
            success:true,
            data,
        }
    } catch (error) {
        ctx.body = {
            success:false,
            message:error.message,
        }
    }
}
const api = new Router()
api.use(ApiRouter())
// 路由的定义还是跟原来一样
// 区别就是,你不需要用到ctx参数了
// 如果一切正常,你直接return
// 如果出现错误,你就抛一个错
api.get('/test', () => {
    if (Math.random() > 0.5) return 'Hello World!'
    else throw new Error('Goodbye World!')
})
// 应用路由
// 建议放到单独的路径下面
router.use('/api', api.routes(), api.allowedMethods());

image.png
image.png


我是好人
2.2k 声望17 粉丝

Erpack 二次封装ant-design-vue,可以看看。


引用和评论

0 条评论