Search code examples
javascriptspring-data-resthateoashalhal-json

How do I use JavaScript Traverson HAL $all meta selector?


Per the JavaScript Traverson HAL documentation

For embedded arrays you can additionally use the meta selector $all, which operates on embedded documents: If you pass ht:post[$all] to the follow method, you receive the complete array of posts, not an individual post resource. A link relation containing $all must only be passed as the last element to follow and it only works for embedded documents. Futhermore, it can only be used with get and getResource, not with post, put, delete, patch or getUri.

However, when I call:

    traverson
        .from("http://localhost:8080/api")
        .follow("cars[$all]")
        .getResource(
            function(error, document) {
                console.log(document);
        });

The browser console logs an empty array for document. The HAL response at http://localhost:8080/api/cars is:

{
  "_embedded" : {
    "cars" : [ {
      "id" : 1,
      "name": "hotrod",
      "_links" : {
          "self" : {
             "href" : "http://localhost:8080/api/cars/1"
          }
      }
    },{
      "id" : 2,
      "name": "junker",
      "_links" : {
          "self" : {
             "href" : "http://localhost:8080/api/cars/2"
          }
      }
   }]
   },
    "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/cars"
    },
    "profile" : {
      "href" : "http://localhost:8080/api/profile/cars"
    }
  }
} 

Why does my call to .follow("cars[$all]") result in an empty array instead an array of car objects?


Solution

  • I needed to follows the cars link and then reference the cars array:

        traverson
        .from("http://localhost:8080/api")
        .follow("cars")
        .follow("cars[$all]")
        .getResource(
            function(error, document) {
                console.log(document);
        });
    

    I thought that cars[$all] was following to the cars resource and [$all] retrieved the embedded array of cars.