mgonto / restangular

AngularJS service to handle Rest API Restful Resources properly and easily
MIT License
7.87k stars 840 forks source link

Nested Hyperlinks: How to consume and array of nested hyperlinks? #1459

Closed samwhale closed 6 years ago

samwhale commented 7 years ago

Currently, my api is returning this on a Restangular.one('cabinet', 1) request:

{
    folders: ['http://localhost:8000/api/folder/1', 
              'http://localhost:8000/api/folder/2',
              'http://localhost:8000/api/folder/3']
}

but i want it to return the folder objects

{
    folders: [{
                  files: ['http://localhost:8000/api/file/1'
                          'http://localhost:8000/api/file/2']
              }, 
              {
                  files: ['http://localhost:8000/api/file/3']
              },
              {
                  files: ['http://localhost:8000/api/file/4']
              }]
}

(and then the file objects inside the folder objects):

{
    folders: [{
                  files: [{},{}]
              }, 
              {
                  files: [{}]
              },
              {
                  files: [{}]
              }]
}

How can I configure restangular through addResponseInterceptor or other means to consume the array of nested hyperlinks?

samwhale commented 7 years ago

I have not found a solution which performs a get() on all nested urls independently without doing it explicitly in the controller.

So for these twice nested jsons, I created three different objects rather than one full cabinet object. Restangular than can use its put and patch methods on the objects returned.

Then I iterate through each folder in the cabinet, and in turn each file in the folder to get all my objects into the view.

If anybody has a better way let me know!

vm.cabinet = {};
vm.folders = [];
vm.files = {}

Cabinets.get(id).then(cabinetSuccessFn, errorFn);

function cabinetSuccessFn(response) {
        vm.cabinet = response;
        vm.cabinet.folders.map(function(folder) {
          return Folder.get(parseInt(folder.substr(folder.lastIndexOf('/', folder.length - 2) + 1).slice(0, -1))).then(folderSuccessFn, errorFn);
        });
        vm.loading = false;
      }

function folderSuccessFn(response) {
        vm.folders.push(response);
        vm.files[response.id] = [];

        response.files.map(function(file) {
          return Files.get(parseInt(file.substr(file.lastIndexOf('/', file.length - 2) + 1).slice(0, -1))).then(fileSuccessFn, errorFn);
        });
      }

function fileSuccessFn(response) {
        vm.filess[response.folder.substr(response.folder.lastIndexOf('/', response.folder.length - 2) + 1).slice(0, -1)].push(response);
      }

function errorFn(response) {
    $log.error('unable to load resource');
    $log.error(response);
}

Not shown: Cabinets, Folders, and Samples services