#nodejs# 統一返回結果處理類

/utils/constant.js

module.exports = {
    ERR_CODE: -1,
    SUCC_CODE: 0
}

/models/Result.js

const {ERR_CODE, SUCC_CODE} = require('../utils/constant')

class Result {
    constructor(data, msg='操作成功', options) {
        this.data = null
        if (arguments.length === 0) {
            this.msg = '操作成功'
        } else if (arguments.length === 1){
            this.msg = data
        } else {
            this.data = data 
            this.msg = msg
            if (options) {
                this.options = options
            }
        }
    }
    json(res) {
       return res.json(this.createResult())
    }
    createResult() {
        if (!this.code) {
            this.code = SUCC_CODE
        }
        let base = {
            code: this.code,
            msg: this.msg
        }
        if (this.data) {
            base.data = this.data
        }
        if (this.options) {
            base = {...base, ...this.options}
        }
        return base
    }
    success(res) {
        this.code = SUCC_CODE
        return this.json(res)
    }
    fail(res) {
        this.code = ERR_CODE
        return this.json(res)
    }
}

module.exports = Result

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章