Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js afterFind argument explanation

I'm trying to implement an afterFind hook on a model and can't quite figure out what the semantics are. I'll pulled the following together from trial and error using the doc and other StackOverflow questions as guidelines.

My goal is to massage the result (by applying get(plain : true)) and pass the transformed value as the result of the promise. For instance, I'd expect/want this to return an empty result set:

        hooks: {
            afterFind: function(result, options, fn)
            {
                result = [];
            }
        },

but it just causes the request to hang. Documentation says the arguments are pass by reference and doesn't include a return. Other samples imply something like:

        hooks: {
            afterFind: function(result, options, fn)
            {
                result = [];
                return fn(null, result);
            }
        },

which doesn't hang, but doesn't change my result set. Not to mention, I've no idea what the magical "fn" argument is/does.

like image 359
Jim O'Neil Avatar asked Oct 30 '15 20:10

Jim O'Neil


1 Answers

I had a similar problem. This is because when you do a findAll the argument passed to the hook is an array of values instead of a single object. I did this as a workaround -

hooks: {
        afterFind: function(result) {
            if(result.constructor === Array) {
                var arrayLength = result.length;
                for (var i = 0; i < arrayLength; i++) {
                    result[i].logo = "works";
                }
            } else {
                result.logo = "works";
            }
            return result;
        }
}

In the above code I change the logo attribute of the record(s) after finding it.

like image 138
romeo14 Avatar answered Oct 12 '22 20:10

romeo14