get() is returning arrays as non-arrays

113 views Asked by At

I have this model:

let model = new falcor.Model({
    cache: {
        hStudents: {
            801: {
                FirstName: 'Samuel',
                LastName: 'Forbes'
                },
            802: {
                FirstName: 'Chad',
                LastName: 'Pennington'
                }
            },
        lStudents: [
            $ref(['hStudents', 801]),
            $ref(['hStudents', 802])
            ]
        }
    });

When I execute the following code, although lStudents is an array in the model, I'm getting back an object which is not an array. For that reason, I cannot use Angular's *ngFor to iterate over the object. Why would I not get an array back?

return this.model.get("lStudents[0..1]['FirstName','LastName']")
    .progressively()
    .subscribe( (h) => {
        console.log(JSON.stringify(h));
        });

prints:

{"json":{
  "lStudents":{
    "0":{"$__path":["hStudents","801"],"FirstName":"Samuel","LastName":"Forbes"},
    "1":{"$__path":["hStudents","802"],"FirstName":"Chad","LastName":"Pennington"},"$__path":["lStudents"]}
  }
}
1

There are 1 answers

0
James Conkling On

Falcor treats arrays as objects with keys equal to the array item's index. See the documentation example here.

The reason for this is that because the lStudents list is paginated, it will have to handle queries like "lStudents[10..19]['FirstName','LastName']". If the result were to be an array rather than object, e.g. { "json": "lStudents": [ <items 10 - 19> ] }, it would conflict with a similar query asking for students 0 - 9 (or any other student list query).

To handle objects representing lists, convert the jsonGraph response to an array. A utility library like lodash or ramda might come in handy.

this.model.get("lStudents[0..1]['FirstName','LastName']")
    .progressively()
    .subscribe((jsonEnvelope) => {
       /* using Ramda and transforming 
        * { "FirstName":"Samuel","LastName":"Forbes" }
        * to { "FirstName":"Samuel","LastName":"Forbes", "index": "0" }
        */
        console.log(
          R.compose(
            R.map(([studentIdx, student]) => ({
              ...student,
              index: studentIdx
            })),
            R.toPairs
          )(jsonEnvelope.json.lStudents);
        );
        /* using Ramda and ignoring index
         */
        console.log(
          R.values(jsonEnvelope.json.lStudents)
        );
 });