Monday, 3 April 2017

Is it safe to temporarily overwrite a prototype method in express' route handler?

I have a situation where I have an object with a lot of Date instances in it. The object is then transformed into JSON, and returned:

router.post('/', function () {
    // Some code that returns the object
    res.status(200).json(object);
});

I need to change how all of the Date objects are converted to JSON, so I was thinking of doing this:

router.post('/', function() {
    var originalToJSON = Date.prototype.toJSON;
    Date.prototype.toJSON = function() {
        return moment(this).format(...); // some formatting function
    }
    res.status(200).json(object);
    Date.prototype.toJSON = originalToJSON;
});

I realize this is a terrible practice, but I'm curious what the implications are. Since I'm restoring Date.prototype.toJSON to it's original state right after the object is converted to JSON, is it possible that requests that come in meanwhile res.status(200).json(object) is running, and get the overwritten Date.prototype.toJSON?



via ItsGreg

No comments:

Post a Comment