ghassen lassoued
ghassen lassoued

Reputation: 59

How to call remote method of one persisted model inside another remote method of another persisted model

here's what I tried in model1.js:

      model1.remotemethod1 = function(id, data, cb) {
var model2 = app.models.model2;
model2.remotemethod2(id, data).then(response => {
cb(null, true);
});
 };

this is my model2.js : it has the definition of remotemethod2 .

 'use strict';

  module.exports = function(model2) {

  model2.remotemethod2 = function(id, data, cb) {
     var promise;
     let tags = data.tags ? data.tags.slice() : [];
     delete data.categories;
     delete data.tags;
     promise = model2.upsertWithWhere({
             or: [
                 {barcode: data.barcode},
                 {id: data.id},
             ],
         }, data);
     promise.then(function(model2) {
         model2.tags.destroyAll().then(function() {
             for (let i = 0; i < tags.length; i++) {
                 model2.tags.add(tags[i]);
             }
             cb(null, model2);
         });
     });
    };
 };

But it dos not work ! I think that app.models.model2 does not give me the model with its remote methods ! maybe I should get an instance of the model2 !

Upvotes: 1

Views: 1635

Answers (2)

user10590145
user10590145

Reputation:

var (VAR-NAME)= (CURRENT-MODEL).app.models.(ANOTHER_MODEL);

you now can use the other model by calling one of its methods for example

EX:

VAR-NAME.create();

Upvotes: 2

user8120138
user8120138

Reputation:

Declare remotemethod1 in server.js app.start and you'll have access to the correct app.models.model2 and you will be able to use its remote method.

app.start = function() {
     model1.remotemethod1 = (id, data, cb) =>  {
        var model2 = app.models.model2;
        model2.remotemethod2(id, data).then(response => {
           cb(null, true);
        });
     };

      model1.remoteMethod(
        'remotemethod1', {
            http: { path: '/remotemethod1', verb: 'post', status: 200, errorStatus: 400 },
            accepts: [{arg: 'id', type: 'number'}, {arg: 'id', type: 'object'}],
            returns: {arg: 'status', type : 'string' }
        }) ;
    }  

    //  The rest of app.start...

EDIT you can also create the remote method will the correct app context with a file located in myprojectname/server/boot

`module.exports(app) {
     /* Create remote methods here */
}`

Upvotes: 2

Related Questions