restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Nested Associations

Open mrdanparker opened this issue 13 years ago • 11 comments

Hi,

I was wondering if there was any way to "restangularize" nested associations without having to perform two API calls? i.e. Say I had a /ships endpoint and everywhere I use a ship I always need to know about it's crew. My API actually returns the crew information as part of the response. e.g. /ships/1 returns:

    {
        id:1, 
        name: "Queen Anne's Revenge", 
        crew: [{
            id:1, 
            name: "Blackbeard"
        }]
    }

What I'd like to be able to do is somehow let restangular know that my response contains a crew collection and that it should also be restangularized to give me all the restangular method decoration goodness on the crew members.

This would also be useful on 'has one" associations too. ie. (for want of a better example) If requesting by crew member first: /crew/1 returning:

    {
        id:1, 
        name: "Blackbeard", 
        ship: {
            id:1, 
            name: "Queen Anne's Revenge"
        }
    }

It'd be good if we were able to tell it to restangularize Blackbeard's ship.

Great library BTW - Thanks,

Dan

mrdanparker avatar Jun 05 '13 09:06 mrdanparker

Hey,

Thanks for reporting the issue!

Regarding the inquiry, there's no way for Restangular to know which are "asociation" resources, which are not, and which is the URL of this "asociation" resources.

Do you have any suggestion of an API or on how to recognize or create this?.

In the case of Blackbeard, the URL for Blackbeard would be /people/1 and for the ship it'd be /people/1/ship/1?

What I could do is expose the "restangularize" method to outside, and in the hook onElementRestangularized, what you could do is something like this:

RestangularProvider.setonElemRestangularized(function(elem, isCollection, what) {
  if (!isCollection && what === 'people') {
   // Where restangularizeElement signature would be (object, parent, path)
    elem.ship = Restangular.restangularizeElement(elem.ship, elem, 'ships');
  }
})

If this makes sense to you, I could expose this already existing method, and then you could create this nested asociations resources when needed for the object you actually need.

Or, you may describe asociations in some DSL, and that would create this nested asociations for you, buy either way, you're going to need to tell Restangular which are those.

mgonto avatar Jun 05 '13 23:06 mgonto

Yeah, initially I was thinking what you said about exposing the "restangularize" method so that it can be called from the onElementRestangularized hook. Would be great if you could do that?

As for an API, how about if there was a withAssociations method that takes a properties map with a form something along the lines of:

{
    many: ['crewMembers', 'prisoners'],
    one: ['captain', 'preciousCargo']
}

Then once the response is returned it (the library) knows it needs to restangularize a collection of crewMembers, a collection of prisoners, a single captain, and a single preciousCargo. The strings would be both the property on the JSON, plus will double up as the route (chained with the parent route). Or maybe each of the items in the many and one arrays should be maps themselves so that their routes/other stuff can be configured. I may be overcomplicating now!

So ultimately, you'd be able to do:

Restangular.one('ships', 1).withAssociations({many:['crewMembers'], one:['captain']})

Thoughts?

Anyway, in the meantime just exposing "restangularize" would be great.

mrdanparker avatar Jun 06 '13 11:06 mrdanparker

Hey,

I think it'd be something like

Restangular.one('ships', 1).getWithAsociations(...) as it'd do the request at that moment instead of adding this "nested calls"

Also, in there, you're just specifying the name of the field (crewMembers) you need to specify the route as well.

I don't know if it'd be better to specify this in the RestangularProvider like:

RestangularProvider.setAsociations({
  ships: {
    many: {
      route: 'captains',
      field: 'allCaptains'
  }
})

Or (continuing thinking at loud :)), maybe just by adding this hook to restangularize elements in the onElemRestangularized is enough.

I don't know which is the best way, but in every ships request, specifying the asociations with routes and fields, isn't ideal. You need to fill to much information there for it to work.

I like that Restangular needs very little configuration and it actually just works. This would add much more configuration.

I think I'm going to add the restangularizeElement and maybe if you wanted to use it like that, you could create a Wrapper for Restangular that does this, so that way, Restangular is still generic and you could add your own Wrapper or plugin.

Does this make sense?

mgonto avatar Jun 06 '13 20:06 mgonto

I've changed this to enhancement to implement this :) and so that it can be used in onElemRestangularized at least.

mgonto avatar Jun 06 '13 20:06 mgonto

Good point; Having to define the (verbose) associations for every request wouldn't be particularly DRY. Personally I like the RestangularProvider.setAsociations( ... ) solution. It seems cleaner than hooking into the onElemRestangularized and doing it yourself. But in terms of getting something out there that's usable, exposing restangularizeElem / Collection is just what I need :)

mrdanparker avatar Jun 07 '13 09:06 mrdanparker

Methods pushed.

Now you have Restangular.restangularizeElement(parent, elem, route, Restangular.restangularizeCollection(parent, elem, route).

And the onElemRestangularized receives a 4 parameter which is the service itself so that you can use this added methods.

Hope this works out well for you :)

mgonto avatar Jun 09 '13 22:06 mgonto

Like a charm! Thanks a lot :)

mrdanparker avatar Jun 10 '13 12:06 mrdanparker

No problem!

mgonto avatar Jun 10 '13 15:06 mgonto

Still not getting the complete picture how you would cleanly implement the case above if "crew" was a collection.

I understand that Restangular.restangularizeCollection(parent, elem, route) is responsible to restangularize the "crew" collection, but from where would i call it?

I tend to hide my Restangular object behind a service and configure them with Restangular.withConfig(). Where would I place the call to restangularizeCollection then?

ghost avatar Oct 07 '15 14:10 ghost

Hi @mgonto , same problem like @airlst . My restangular object is on a service, and the configuration on a config file for all the app. Where would I place the call to restangularizeElement?

BTW, what I get from my api is a thing like this:


{
  "total": 2,
  "per_page": 10,
  "current_page": 1,
  "last_page": 1,
  "next_page_url": null,
  "prev_page_url": null,
  "from": 1,
  "to": 2,
  "data": [
    {
      "id": 1,
      "start_date": "2006-08-20 05:11:32",
      "end_date": "2009-10-18 23:03:06",
      "created_at": "2016-06-23 08:41:51",
      "updated_at": "2016-06-23 08:41:51",
      "unity": {
        "id": 224,
        "code": 20060810,
      },
      "user": [
        {
          "id": 1,
          "username": "Kiara Runolfsdottir",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
        {
          "id": 2,
          "username": "Zoe Dach",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
        {
          "id": 3,
          "username": "Mrs. Zelma Johnston III",
          "created_at": "2016-06-23 15:56:56",
          "updated_at": "2016-06-23 15:56:56"
        },
      ]
    }
  ]
}

and my servicel is this:


'use strict';

angular.module('ng-laravel').service('ScaleService', function($rootScope, Restangular,CacheFactory) {
    /*
     * Build collection /scale
     */
    var _scaleService =  Restangular.all('scale');

    if (!CacheFactory.get('scalesCache')) {
        var scalesCache = CacheFactory('scalesCache');
    }

    /*
     * Get list of users from cache.
     * if cache is empty, data fetched and cache create else retrieve from cache
     */
    this.cachedList = function() {
        // GET /api/scale
        if (!scalesCache.get('list')) {
            return this.list();
        } else{
            return scalesCache.get('list');
        }

    };


    /*
     * Get list of users
     */
    this.list = function() {
        // GET /api/scale
        var data = _scaleService.getList();

        scalesCache.put('list',data);
        return data;
    };



    /*
     * Pagination change
     */
    this.pageChange = function(pageNumber,per_page) {
        // GET /api/scale?page=2
        return _scaleService.getList({page:pageNumber,per_page:per_page});
    };


    this.cachedShow = function(id) {
        // GET /api/scale/:id
        if (!scalesCache.get('show'+id)) {
            return this.show(id);
        } else{
            return scalesCache.get('show'+id);
        }
    };

    /*
     * Show specific scale by Id
     */
    this.show = function(id) {
        // GET /api/scale/:id
        var data = _scaleService.get(id);
        scalesCache.put('show'+id,data);
        return data;
    };


    /*
     * Create scale (POST)
     */
    this.create = function(scale) {
        // POST /api/scale/:id
        _scaleService.post(scale).then(function() {
            $rootScope.$broadcast('scale.create');
        },function(response) {
            $rootScope.$broadcast('scale.validationError',response.data.error);
        });
    };

    /*
     * Update scale (PUT)
     */
    this.update = function(scale) {
        // PUT /api/scale/:id
        scale.put().then(function() {
            $rootScope.$broadcast('scale.update');
        },function(response) {
            $rootScope.$broadcast('scale.validationError',response.data.error);
        });
    };


    /*
     * Delete scale
     * To delete multi record you should must use 'Restangular.several'
     */
    this.delete = function(selection) {
        // DELETE /api/scale/:id
        Restangular.several('scale',selection).remove().then(function() {
            $rootScope.$broadcast('scale.delete');
        },function(response){
            $rootScope.$broadcast('scale.not.delete');
        });
    };

    /*
     * Search in scale
     */
    this.search = function(query,per_page) {
        //console.log(query);
        // GET /api/permission/search?query=test&per_page=10
        if(query != ''){
            return _scaleService.customGETLIST("search",{query:query, per_page:per_page});
        }else{
            return _scaleService.getList();
        }
    }



});

Tnks !

fstbraz avatar Jun 28 '16 09:06 fstbraz

Ok, after a one day fight, finally I find a solution for my edit route list problem: Something simple using a javascript promise:

this.show = function(id) {
        // GET /api/scale/:id
        var data =  _scaleService.getList().then(function (users) {
            var data = users[id-1];
            scalesCache.put('show' + id, data);
            return data;
        }) 
      return data;
};

@mgonto I suggest a better documentation about nested objects. Tnks for this amazing plugin!

fstbraz avatar Jun 29 '16 09:06 fstbraz