egg icon indicating copy to clipboard operation
egg copied to clipboard

Getter/Setter does not work with ES6 class in extend/context.ts

Open minhthinhls opened this issue 4 years ago • 1 comments

What happens?

Context Getter/Setter does not work with ES6 class.

    class Context {
        constructor() {
        }
        /**
         ** - Return all operators of Sequelize
         ** @url https://demopark.github.io/sequelize-docs-Zh-CN/querying.html
         **/
        get Op() {
            return this.app.Sequelize.Op;
        }
        get print() {
            return this.body;
        }
        get realIP() {
            return this.get['X-Real-IP'] || this.get['X-Forwarded-For'] || this.ip;
        }
        /**
         ** @param {*} value
         ** @example
         ** ctx.print = 'Hello'
         ** ctx.print = null
         ** ctx.print = {name: 'Hello'}
         ** @returns {void}
         **/
        set print(value) {
    
            const body = {
                data: value,
                errorCode: 0,
                msg: ERROR_CODE[0],
                success: true
            };
    
            if (isPlainObject(value)) {
    
                if (value.errorCode !== undefined && value.errorCode !== 0) {
                    body.errorCode = value.errorCode;
                    body.success = false;
                    body.msg = ERROR_CODE[body.errorCode] || 'error';
                    body.data = null;
                }
    
                body.msg = value.msg || body.msg;
                body.errorMsg = value.errorMsg || body.msg;
    
                // Delete duplicate defined fields
                if (isPlainObject(body.data)) {
                    body.data = Object.assign({}, body.data);
                    delete body.data.errorCode;
                    delete body.data.msg;
                    delete body.data.success;
                }
            }
    
            this.body = body;
        }
    }
    
    // export default new Context();
    
    module.exports = new Context();

Steps to reproduce the behavior:

  1. The setter and getter do not run when I use ctx.print = <...something...>

Expected behavior

  1. It should Run

Context

  • Node Version: 14
  • Egg Version: 2.30
  • Platform: NodeJS

minhthinhls avatar Nov 10 '21 14:11 minhthinhls

Please take a look at: egg-core/lib/loader/mixin/extend.js#loadExtend() on line 115 Properties will resolved into empty Array when using ES6 class instance [], but for PlainObject it can be resolved into [ 'Op', 'print', 'realIP' ]; Since method from class will be resoved as Inherit Prototype, not OwnPropertyNames.

const properties = Object.getOwnPropertyNames(ext).concat(...);

minhthinhls avatar Nov 11 '21 04:11 minhthinhls