Search code examples
node.jspostloopbackjsloopback

How to access function another model in loopback?


I have two model Place and Tag. I created creteTag() remote methode in tag.js and I would like to access this functinon in place.js.

tag.js

'use strict';
var request = require('request');
module.exports = function(Tag) {
Tag.crateaTag = function(name, callback) {
    request({
        method: 'POST',
        url: 'http://localhost:3000/api/tags',
        body:{
            "name": name
        },
        json: true
     },
     function (error, response,body) {
        if (error || response.statusCode != 200) {
           console.log('Hiba' + error + ' \n' + response);
        }
        callback(error, body);
     });
};

place.js

'use strict';
var request = require('request');
module.exports = function(Place) {
var app = require('../../server/server');
Place.createPlace = function(name, descreption, tagName, callback) {
    var Tag = app.models.Tag; //???

    request({
        method: 'POST',
        url: 'http://localhost:3000/api/tags',
        body:{
            "name": name,
            "descreption": descreption,
            "tag": Tag.createTag(tagName) //???
        },
        json: true
     },
     function (error, response, body) {
        if (error || response.statusCode != 200) {
           console.log('Hiba' + error + ' \n' + response);
        }
        callback(error, body);
     });
  };
};

I would like to post the tag that I would like to see separate collection in my db.


Solution

  • In tag.js declare crateaTag as remote method:

    Tag.remoteMethod('crateaTag', {
    accepts: {
        arg: 'name',
        type: 'string',
        required: true
        },
        description: "create a tag"
    });
    

    In place.js use Tag as:

    var Tag = app.models.Tag;
    Tag.createTag('test', function(){
    // do your stuff
    });