Search code examples
ember-cliember-cli-mirage

Ember 2.5 ember-cmi-mirage trying to get a subset of collection


Using ember 2.5 and ember-cli-mirage 0.2)

In my mirage/config.js , I am trying to get a subset ofa collection, for pagination purpose) using the slice() function

var books = schema.book.all().slice(startItem, endItem );

but I get an error:

schema.book.all(...).slice is not a function

I tried also , same error

var books = schema.book.all();
var items = books.slice(startItem, endItem );

Here is my mirage/config.js export default function() { .... this.get('/books', function(schema, request) {

        const pageNumber = request.queryParams['page[number]'];
        const pageSize = request.queryParams['page[size]'];

        const startItem= (pageNumber - 1) * pageSize;
        const endItem = (pageNumber * pageSize) - 1;

        var books = schema.book.all().slice(startItem, endItem );

        ....

        return books;
      });
    }

It seems that slice() is a function of ArrayProxy.. however this may not help as with a JSONAPISerializer

I'm a little bit lost as all exampels I can google relate to Ember 1.13 and not Ember 2.5...


Solution

  • This is because Collection is array-like, but not a true array. Precisely for this reason, in the next beta release we'll expose a .models property which has the underlying array.

    For now, try calling .toArray() on your schema.book.all() collection, and then calling slice on it.

    To take advantage of the Serializer layer, make sure to return a new Collection from your handler:

    import Collection from 'ember-cli-mirage/orm/collection';
    
    this.get('/books', (schema, request) => {
      let books = schema.book.all().toArray().slice(...);
    
      return new Collection('book', books);
    });