How do I get the item count (size) of a dojo datastore?
-
06-07-2019 - |
Question
I don't see anything in the read API that provides access to this: http://api.dojotoolkit.org/jsdoc/1.3.2/dojo.data.api.Read
Solution
The format of the wire-data of any data store is completely store-specific. In order for you to get the total items count (and other metadata), it must be returned as part of the response. This is the only way to do server-side pagination.
All the stores I have implemented expect the data to contain a totalCount
attribute, like so:
{
identifier: 'id',
items: [
{ id: 123, name: 'aaa', ... },
{ id: 456, name: 'bbb', ... },
...
],
totalCount: 525
}
The store saves this when the query returns (in onComplete
). The value is then exposed via a getTotalCount()
method on the store.
When used in conjunction with the start
and count
request options, this allows you to have nice ajax pagination ("Showing 1-50 of 525").
Since this is not part of the API, the core implementations of the read API do not implement it. A form of this technique (similar to what I have done) does seem to be implemented by the dojo.data.QueryReadStore
, so you can probably look there also.
OTHER TIPS
An example at dojocampus demonstrates one way. Here a fetch
without query
parameter returns all the items in the store.
var store = new some.Datastore();
var gotItems = function(items, request){
console.log("Number of items located: " + items.length);
};
store.fetch({onComplete: gotItems});
dojo.data.api.Read's onBegin function has the total size of the match:
function size(size, request){
// Do whatever with the size var.
}
store.fetch({query: {}, onBegin: size, start: 0, count: 0});
From this quickstart: http://dojotoolkit.org/reference-guide/1.7/quickstart/data/usingdatastores/faq.html#question-6-how-do-i-get-a-count-of-all-items-in-a-datastore
I was looking for the answer to this question using the JsonRest store, and this seems to be it:
On your server, you should look at the Range header in the request to know which items to return. The server should respond with a Content-Range header to indicate how many items are being returned and how many total items exist:
Content-Range: items 0-24/66
From: http://dojotoolkit.org/reference-guide/dojo/store/JsonRest.html
The following code worked for me
// questionStoreReader is a pointer that points to and can read ask.json file
var questionStoreReader=new dojo.data.ItemFileReadStore({url:"ask.json"});
questionStoreReader.fetch(
{
onComplete:function(items,request) // items is an array
{
alert(items.length);// number of items in ask.json
},
})