Update collection API.

This commit is contained in:
Julien Fontanet 2015-02-20 17:14:44 +01:00
parent 6725cc6f61
commit a0a1353445
2 changed files with 37 additions and 24 deletions

View File

@ -75,13 +75,24 @@ console.log('Current user is', xo.user);
XO objects are cached locally in the `objects` collection.
```javascript
// Get an object for a specific id.
var obj = xo.objects.get(id);
// Read-only dictionary of all objects.
var allObjects = xo.objects.all;
// Get all VMs.
var vms = xo.objects.where('type', 'VM');
// Looks up a given object by its identifier.
var object = allObjects[id];
// Read-only dictionary of all indexes.
var indexes = xo.objects.indexes;
// Read-only dictionary of types.
var byTypes = indexes.type;
// Read-only view of all VMs.
var vms = byTypes.VM;
```
Available indexes are: `ref`, `type` and `UUID`.
## Low level
```javascript

View File

@ -13,6 +13,16 @@ function defaultKey(item) {
//====================================================================
function getAll() {
/* jshint validthis: true */
return this._all;
}
function getIndexes() {
/* jshint validthis: true */
return this._indexes;
}
function Collection(opts) {
if (!opts) {
opts = {};
@ -28,6 +38,18 @@ function Collection(opts) {
}
this._data = Object.create(null);
// Expose public properties.
Object.defineProperties(this, {
all: {
enumerable: true,
get: getAll,
},
indexes: {
enumerable: true,
get: getIndexes,
},
});
}
function createIndex(_, field) {
@ -40,26 +62,6 @@ Collection.prototype.clear = function () {
forEach(this._indexes, createIndex, this._indexes);
};
Collection.prototype.get = function (key) {
return this._data[key];
};
// Find the first entry in an index for a given value.
Collection.prototype.find = function (field, value) {
return this.where(field, value)[0];
};
// Find all entries in an index for a given value.
Collection.prototype.where = function (field, value) {
var index = this._indexes[field];
if (!index) {
throw new Error('no such index');
}
return index[value] || [];
};
function unsetItemFromIndex(index, field) {
/* jshint validthis: true */