简体   繁体   中英

LoopBack operation hook use multiple models

I've got a question about LoopBack's operation hooks.

With help of what is said here , I'm trying to create a Privilege object programmatically whenever the 'after save' event of my Company model is triggered. This is to have automatically objects created after one is being saved.

Please note that I've simplified my case to make it simple but I will actually create several objects after the creation of a Company .

I have created a script int my common/models/ folder which contains the following code:

module.exports = function (Company) {
    Company.observe('after save', function createObjectsForNewClient(ctx, next) {
    if (ctx.instance) {
        log('A new Company has been created. Shall create a Privilege for it.');

        Privilege.create(
            {...},
            function (err, obj) {
                if(err)
                    console.error(err);

                if(obj)
                    console.lof(obj);
                }
            );
        }
    }
}

With this, the hook is triggered correctly but LoopBack stops with an exception saying:

TypeError: Cannot read property 'Privilege' of undefined

I thought this model would be available from somewhere in some loopback/javascript/almost-magic scope. The thing is that I've also tried adding the Privilege model in the module.exports = function (Company, Privilege) {... block but it does not seem to accept listing an infinite number of models to be used in the function... You should also note that I've created my models into JSON files in the common/models/ folder but no other JS scripts for those models because LoopBack seems to handle the export automatically. Would it have an impact on the fact that they are not accessible as I want ?

I might have done something wrong somewhere but what I'm trying to do seemed fairly simple. Does anyone have an idea ?

Other models are accesible via Model.app.models .

I usually define all the models my remote method or hook requires in the first few lines, for example:

module.exports = function (Company) {
    Company.observe('after save', function createObjectsForNewClient(ctx, next) {
        const Privilege = Company.app.models.Privilege,
              OtherModel = Company.app.models.OtherModel;
        // the rest of your operation hook

Note that you have to do this for every method. This won't work because models are not bootstrapped at compilation time:

module.exports = function (Company) {
    // won't work
    const OtherModel = Company.app.models.OtherModel;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM