scotthovestadt / schema-object

Enforce schema on JavaScript objects, including type, transformation, and validation. Supports extends, sub-schemas, and arrays.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Super() arguments are ignored in favor of overriding method's arguments

wbaaron opened this issue · comments

First off, thanks for this module. It's been a huge help setting up my project. I've run into an issue that I've changed on my local copy, but I wanted to get your feedback on it.

Refer to the use of _arguments instead of arguments on line 1255 below.

mergedOptions[methodHome][name] = function () {
var _this22 = this,
_arguments = arguments;
this[_privateKey]._reservedFields.super = function () {
return method.apply(_this22, _arguments);
};
var ret = extendOptions[methodHome][name].apply(this, arguments);
delete this[_privateKey]._reservedFields.super;
return ret;
};

This means we can't pass arguments to the overridden method. It uses the overriding method's argument regardless of what is passed in super(). Is this done on purpose?

A simplified example of what I'm trying that is not working:

Order.js

const Order = new Schema({
    id: Number,
    items: [Item]
}, {
    methods: {
        save: async function(db) {
            let result = await db.write(this.id, this.toObject());
            return result === 'OK';
        }
    }
});

PurchaseOrder.js

const Order = require('./Order');
const database = new require('./Database')(Order.Type.PURCHASE_ORDER);

const PurchaseOrder = Order.extend({
    expected_receipt_date: Date,
    memo: String,
}, {
    methods: {
        save: async function() {
            return await this.super(database);
        }
    }
});

POST.js

const PurchaseOrder = require('../models/PurchaseOrder');

module.exports = {

    // Receive new Purchase Order data and save to database
    purchaseOrder: async (req, res) => {
        let po = new PurchaseOrder(req.body);
        let result = await po.save();
        res.send(result);
    }
}

The PurchaseOrder 'sub-class' connects to the specific database it needs and stores a reference to it. Then I call po.save(), which in turn calls super.save(database) and sends that database info the parent class save method, which should run the query on the given database.

Because of line 1255 above, the database object passed to super() is thrown away in favor of po.save()'s empty arguments array. Result is a TypeError of "Cannot read property of 'write' of undefined". This doesn't make much sense to me, but I may be missing the reason.

Please let me know your thoughts.