как сделать разбиение на страницы, используя поддельные данные миража в emberjs?

Я использую Mirage для создания поддельных данных.

сценарий/default.js

export default function(server) {
  server.createList('product', 48);
  server.loadFixtures();
}

Выше я создаю 48 продуктов и звоню с контроллера

this.store.query('product', {
                filter: {
                    limit: 10,
                    offset: 0
                }
            }).then((result) => {
                console.log(result);
            });

и в mirage/config.js

this.get('/products', function(db) {
    let products = db.products;
    return {
      data: products.map(attrs => ({
        type: 'product',
        id: attrs.id,
        attributes: attrs
      }))
    };
  });

теперь мой вопрос, как загрузить 10 продуктов на страницу? Я отправляю фильтр 10, так как размер страницы и смещение означают номер страницы.

какие изменения нужно внести в config.js, чтобы загружать только ограниченные продукты?


person murli2308    schedule 10.05.2016    source источник


Ответы (2)


В вашем обработчике в mirage/config.js:

this.get('/products', function(db) {
    let images = db.images;
    return {
      data: images.map(attrs => ({
        type: 'product',
        id: attrs.id,
        attributes: attrs
      }))
    };
  });

Вы можете получить доступ к объекту запроса следующим образом:

this.get('/products', function(db, request) {
    let images = db.images;
    //use request to limit images here
    return {
      data: images.map(attrs => ({
        type: 'product',
        id: attrs.id,
        attributes: attrs
      }))
    };
  });

Взгляните на это твиддл для полного примера. Где this twiddle имеет следующее:

  this.get('tasks',function(schema, request){
    let qp = request.queryParams
    let page = parseInt(qp.page)
    let limit = parseInt(qp.limit)
    let start = page * limit
    let end = start + limit
    let filtered = tasks.slice(start,end)
    return {
      data: filtered
    }
  })

Вы просто адаптируете его для своего использования следующим образом:

  this.get('products',function(db, request){
    let qp = request.queryParams
    let offset = parseInt(qp.offset)
    let limit = parseInt(qp.limit)
    let start = offset * limit
    let end = start + limit
    let images = db.images.slice(start,end)
    return {
      data: images.map(attrs => ({
        type: 'product',
        id: attrs.id,
        attributes: attrs
      }))
    }
  })
person TameBadger    schedule 10.05.2016
comment
это работает хорошо. спасибо. Я заменил db.images на db.products, вы также можете изменить его. - person murli2308; 11.05.2016

Пример с todos, вы можете адаптировать его к своему варианту использования.

    // Fetch all todos
    this.get("/todos", (schema, request) => {
        const {queryParams: { pageOffset, pageSize }} = request
        
        const todos = schema.db.todos;
    
        if (Number(pageSize)) {
            const start = Number(pageSize) * Number(pageOffset)
            const end = start + Number(pageSize)
            const page = todos.slice(start, end)
        
            return {
                items: page,
                nextPage: todos.length > end ? Number(pageOffset) + 1 : undefined,
            }
        }
        return todos
    });
person Felix Op    schedule 20.09.2020