diff --git a/packages/xo-lib/README.md b/packages/xo-lib/README.md index 0f735d982..6e29a1b3d 100644 --- a/packages/xo-lib/README.md +++ b/packages/xo-lib/README.md @@ -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 diff --git a/packages/xo-lib/collection.js b/packages/xo-lib/collection.js index ee8277f7c..0cf1913ee 100644 --- a/packages/xo-lib/collection.js +++ b/packages/xo-lib/collection.js @@ -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 */