Using Dexie with Typeson

Preserving custom types dynamically in indexedDB by using Typeson.

by David Fahlander

HTML

<!-- Include dexie.js -->
<script src="https://npmcdn.com/dexie/dist/dexie.js"></script>
<script src="https://npmcdn.com/typeson/dist/typeson.js"></script>

<!-- Some HTML for the log window -->
<a href="http://dexie.org/docs/API-Reference" target="_new">Dexie API Reference (new tab)</a>
<h3>Log</h3>
<textarea id="log"></textarea>

<!-- Just a simple log function... --> 
<script>
  function log(txt) {document.getElementById('log').value+=txt+"\n";}
</script>

CSS

textarea#log
{
    width: 100%;
    height: 1000px;
}

JavaScript

//
// Custom classes
//

class Friend {
  constructor (name, age, cars) {
    this.name = name;
    this.age = age;
    this.cars = cars;
  }
  
  sayHello() {
    log("Hi, I am " + this.name + ", " + this.age + "!");
  }
  
  listCars() {
  	return this.cars.map(car => car.brandAndModel());
  }
}

class Car {
  constructor (brand, model) {
    this.brand = brand,
    this.model = model;
  }
  
  brandAndModel() {
    return this.brand + " " + this.model;
  }
}

// Configure typeson
var TSON = new Typeson().register({
    Friend,
    Car
});

//
// Define database
//
var db = new Dexie("MyTypesonDB");
db.version(1).stores({
	friends: '++id,name,age'
});
log ("Using Dexie v" + Dexie.semVer);
//
// Query Database
//
db.open().then(() => {
  const car = new Car("Volvo", "v70");
  const friend = new Friend("Foo", 42, [car]);
  return db.friends.add(TSON.encapsulate(friend));
}).then(() => {
  return db.friends
      .where('age')
      .between(30,45)
      .toArray();
}).then(friends => {
	return friends.map(TSON.revive);
}).then(friends => {
  log("Testing if a friend can say hello...");
  friends[0].sayHello();
  log("Testing if we can list cars for a friend...");
  const cars = friends[0].listCars();
  log("Got car list: " + cars);
}).then(function(){
	return db.delete(); // So you can experiment again and again...
}).catch (Dexie.MissingAPIError, function (e) {
	log ("Couldn't find indexedDB API");
}).catch ('SecurityError', function(e) {
  log ("SeurityError - This browser doesn't like fiddling with indexedDB.");
  log ("Go run some samples instead at: https://github.com/dfahlander/Dexie.js/wiki/Samples");
}).catch (function (e) {
	log (e);
});