How to set a uniform return status code in koa?

1. I am a novice, read a lot of documents, and use koa2 + koa-generator + monogoDB to build a demo, to try to write some simple interfaces.
but the question is, how to format the returns uniformly? Or how does my project directory need to be set up and how does the structure need to be optimized?

:

2. For example: query the user"s interface, the code is as follows

const router = require("koa-router")()
const db = require("monk")("127.0.0.1:27017/test1") //

router.prefix("/queryUsers") //

let table1Data = db.get("table1");  
router.get("/", async function (ctx, next) {
    let getParams = ctx.request.query;
    ctx.response.type = "application/json";
    if(getParams._id){
        ctx.body = {
            code:200,
            msg:"success",
            content:await table1Data.find({_id:getParams._id})
        }
    }else {
        ctx.body = {
            code:0,
            msg:"error",
            content:""
        }    
    }
})

module.exports = router

3. Data can be queried through get requests, but how to uniformly format the returns?
cannot always be written separately for each interface:

if(getParams._id){
    ctx.body = {
        code:200,
        msg:"success",
        content:await table1Data.find({_id:getParams._id})
    }
}else {
    ctx.body = {
        code:0,
        msg:"error",
        content:""
    }    
}

4. Or if there are any other optimization suggestions. Crabs, bosses


encapsulates an extra component, and I happen to write a similar one here.

let responseBeautifier = new class{
    constructor(){
        this.response = {
            code:"",
            data:{},
            msg:""
        },
        this.StatusCode = new Map();
        this.registeStatusCode("0","OK");
        this.registeStatusCode("-1","ERROR");
    }
    registeStatusCode(code,description){
        this.StatusCode.set(code,description);
    }
    registeStatusCodes(arr){
        for(let [code,description] of arr){
            this.StatusCode.set(code,description);
        }
    }
    set(data,code="0",msg){
        code = code.toString()
        if(this.StatusCode.has(code)){
            return {
                code,
                data,
                msg:this.StatusCode.get(code),
            }
        }else{
            // log Something ,here is an unique code
            return {
                code,
                data,
                msg:msg||"Unresolvable Status Code :"+code,
            }
        }
    }
    error(code="-1",msg){
        code = code.toString()
        if(this.StatusCode.has(code)){
            return {
                code,
                data:{},
                msg:this.StatusCode.get(code),
            }
        }else{
            // log Something ,here is an unique code
            return {
                code,
                data:{},
                msg:msg||"Unresolvable Status Code :"+code,
            }
        }
    }
}();

//registe Status Code 

responseBeautifier.registeStatusCodes([
    ["404","NtFound"], 
    ["200","success"],
    ["1",""],
])


export default responseBeautifier;
When using

, code can also use number to re-encapsulate it with an array. It is not a big problem. When programming, you can register new return codes and interpretations in this file at any time.

When using

, you only need import R from responseBeautifier , and
use R.set (data) to get the returned data structure

.

it's up to you to set up controller.

in fact, this reponseBeautifier is relatively simple. You can also write a complete structure if you have special needs. It may be better to create a new object every time you need it, which is more in line with the settings of ctx.body

.

unifies the return format in other words, there is a return format class or handler. For example, I can add middleware to define a ctx.state.success method before, and then ctx.state.success (content) , all in the same way.

Menu