gpt4 book ai didi

javascript - 如何在 emberjs 中使用 Mirage 假数据进行分页?

转载 作者:行者123 更新时间:2023-11-28 15:09:37 26 4
gpt4 key购买 nike

我正在使用 Mirage 来创建虚假数据。

场景/default.js

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

上面我正在创建 48 个产品,并从我正在调用的 Controller

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 进行哪些更改才能仅加载有限的产品?

最佳答案

在 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
}))
}
})

关于javascript - 如何在 emberjs 中使用 Mirage 假数据进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37130637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com