Antimony
Antimony

Reputation: 39451

Retrieved typed objects from IndexedDB

What is the most efficient way to store and retrieve typed Javascript objects in IndexedDB?

The problem is that IndexedDB doesn't store prototype information, so you can only store and retrieve plain objects (or arrays or primitives or a few other types). A workaround I came up with is to explicitly assign __proto__ on objects retrieved from the database. For example, to get a Game object I do

game.__proto__ = Game.prototype;

However, __proto__ assignment has the problem that it is A) technically nonstandard, though supported in practice, and B) deoptimizes the code. In fact, Firefox gives an explicit warning

mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create

Obviously, Object.create isn't a possibility here. Are there any better alternatives to __proto__ assignment?

Upvotes: 2

Views: 431

Answers (1)

Josh
Josh

Reputation: 18690

You could consider storing just the backing-data object itself. Game would become just a proxy for a storable object.

function Game(props) {
  this.props = props || {};
}

// An example of property decoration
Game.prototype.set x(value) {
  this.props.x = value;
};
Game.prototype.get x() {
  return this.props.x;
};

// Use this when initializing a game after retrieving game data from indexedDB store. 
// e.g. when creating a new game, use var newGame = Game.fromSerializable(props);
Game.fromSerializable = function(props) {
  return new Game(props);
};

// When it comes time to persist the game object, expose the serializable props object
// so that the caller can pass it to store.put/store.add
Game.prototype.toSerializable = function() {
  return this.props;
};

This might be simpler than bothering to deal with what can pass through the structured clone algorithm used by indexedDB for read/write, or using some strange one-off hack that other people might struggle to understand.

Upvotes: 3

Related Questions