Search code examples
loopbackjsstrongloop

Loopbackjs: Cannot cancel a hook (ie: beforeSave)


Actually I'm trying to cancel a hook to avoid duplicate pair entity-name/subname - by a server-side check.

My example is, if an entity already exists with the same name and subname, I'd like it not to be created/persisted.

Here's my code so far in my entity.js:

module.exports = function (ContactType) {
    ContactType.observe('before save', function filterSameEntities(ctx, next) {
        if (ctx.instance) {
            ContactType.find({where: {name: ctx.instance.name, subname: crx.instance.subname}}, function (err, ct) {
                if (ct.length > 0) {
                    //I'd like to exit and not create/persist the entity.
                    next(new Error("There's already an entity with this name and subname"));
                }
            });
        }
        next();
    });
};

Actually the error is correctly displayed, but the entity is still created and I would like that it wouldn't be the case.


Solution

  • Your last next(); statement is always called, hence the save-action always happens.

    You can end further execution using return. Keep in mind that .find() is async, so just adding return inside the callback would still cause that last next(); statement to run.

    Please try this:

    module.exports = function (ContactType) {
        ContactType.observe('before save', function filterSameEntities(ctx, next) {
            if (!ctx.instance) {
                return next();
            }
    
            ContactType.find({where: {name: ctx.instance.name, subname: ctx.instance.subname}}, function (err, ct) {
                if (err) {    // something went wrong with our find
                    return next(err);
                }
    
                if (ct.length > 0) {
                    //I'd like to exit and not create/persist the entity.
                    return next(new Error("There's already an entity with this name and subname"));
                }
    
                return next();
            });
        });
    };