改造Lor的res和req,


引子

我们在使用lor的过程中,处理req的参数和res的返回,大抵上是这样的:

    homeworkRouter:post("/exam/submit", function(req, res, next)
    local examId = tonumber(req.body.examId)
    local body = req.body
    if examId == nil then
        local data = req.body.data
        if data == nil then
            res:json({
                code = errorCode.requestParams,
            })
            return
        end
        body = cjson.decode(data)
        examId = body.examId
    end
    local result, msg = examService:submit(req.student.StudentID, examId, body)
    if type(result) == "number" then
        if not msg then
            msg = ""
        end
        res:json({
            code = result,
            msg = msg,
        })
        return
    end
    res:json({
        code = 99999,
        data = result
    })
    end)

这里面有几个问题,可以看出:

直接导致了,代码过重复,好多东西都要反复的复制,粘贴

那么,在已经抽像了错误处理机制的基础上,我们对res和req进行需要进行进一步的封装

中间件的加入

加入中间件 knowbox.lua ,文件如下:

    local cjson = load 'cjson'
    local log = load 'libs.log.log_helper'
    local request = load 'libs.http.req'
    local response = load 'libs.http.res'
    local error_helper = load "knowbox.common.error"
    local error_code = error_helper.error_code
    local throw = error_helper.throw
    local  function kb(req,res,next)
        function req:get(name,params)
            local val = self.query[name]
            if val == nil then
                val = self.body[name]
            end
            if val == nil and self.body.data then
                val = self.body.data[name]
            end
            if val == nil then
                throw (error_code .REQ_PARAMS,' 缺少'..name )
            end
            if params ~= nil then
                for _,v in ipairs(params) do
                    if val[v] == nil then
                        throw (error_code .REQ_PARAMS,','..name ..'中缺少'..v )
                    end
                end
            end
            return val
        end
        function res:send(ret)
                self:json({
                code = 99999,
                data = ret
            })
        end
        next()
    end
    return kb

然后在我们的应的顶层路由加上这个中间件,如果已经加入了错误处理机制,那么代码就变成了:

    homeworkRouter:post("/exam/submit", function(req, res, next)
        local examId = tonumber(req:get('examId'))
        local body = req:get('body')
        local result, msg = examService:submit(req.student.StudentID, examId, body)
        res:send(result)
    end

嗯,就是要足够好看。

相关内容

    暂无相关文章