Skip to content
Advertisement

Ensure data types in Dexie.js fields

I have a Dexie.js database with the table “businessLayers” in my React application. I’d like to ensure de data types of the tuples inserted in that table. I thought the method Table.defineClass() would do that, but it does not. My db is the following:

JavaScript

I’d like to make not possible to insert an invalid data type on each field. I haven’t found any built-in method to do this. Do you know any? Thank you!

Advertisement

Answer

Table.defineClass() was an old feature in Dexie 1.x for code completion only – no enforcements. The method should have been deprecated. But the functionality you need can be implemented using a DBCore middleware or creating/updating hooks. DBCore middlware would be the most performant solution as it does not need to verify existing data.

Below is a dry coded full example. Please test and reply if it works. It should support String, Number, Boolean, Array, Object, Set, Map, ArrayBuffer, Uint8Array, etc… and even custom classes. If anyone wants to make a package of this code, please go ahead! I think it could be a nice addon to dexie:

JavaScript
Advertisement