mur*_*308 1 javascript ember.js ember-data ember-cli-mirage
我正在使用海市蜃楼来创建虚假数据。
场景/default.js
export default function(server) {
server.createList('product', 48);
server.loadFixtures();
}
Run Code Online (Sandbox Code Playgroud)
上面我正在创建 48 个产品,我正在调用控制器
this.store.query('product', {
filter: {
limit: 10,
offset: 0
}
}).then((result) => {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
并在海市蜃楼/config.js
this.get('/products', function(db) {
let products = db.products;
return {
data: products.map(attrs => ({
type: 'product',
id: attrs.id,
attributes: attrs
}))
};
});
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,如何每页加载 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
}))
};
});
Run Code Online (Sandbox Code Playgroud)
您可以像这样访问请求对象:
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
}))
};
});
Run Code Online (Sandbox Code Playgroud)
看看这个 twiddle的完整示例。在这个 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
}
})
Run Code Online (Sandbox Code Playgroud)
您只需像这样调整它以供您使用:
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
}))
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1716 次 |
| 最近记录: |