确保 Dexie.js 字段中的数据类型

Ensure data types in Dexie.js fields

我的 React 应用程序中有一个带有 table“businessLayers”的 Dexie.js 数据库。我想确保插入 table 中的元组的数据类型。我认为 Table.defineClass() 方法可以做到这一点,但事实并非如此。我的数据库如下:

import Dexie from 'dexie';

const db = new Dexie('MyDB');

db.version(1).stores({
  businessLayers: '++id, layer'
});

const BusinessLayer = db.businessLayers.defineClass({
  id: Number,
  layer: String,
  values: Object
});

export default db;

我想让每个字段都无法插入无效的数据类型。我还没有找到任何内置方法来执行此操作。你知道任何?谢谢!

Table.defineClass() 是 Dexie 1.x 中的一个旧功能,仅用于代码完成 - 没有强制执行。该方法应该已被弃用。但是您需要的功能可以使用 DBCore middleware or creating/updating 挂钩来实现。 DBCore 中间件将是最高效的解决方案,因为它不需要验证现有数据。

下面是干编码的完整示例。请测试并回复是否有效。它应该支持 String, Number, Boolean, Array, Object, Set, Map, ArrayBuffer, Uint8Array 等...甚至自定义 类。如果有人想打包此代码,请继续!我认为它可能是 dexie 的一个不错的插件:

import Dexie from 'dexie';

const db = new Dexie('MyDB');

db.version(1).stores({
  businessLayers: '++id, layer'
});

// Use a DBCore middleware "enforceSchema" defined further down...
db.use(
  enforceSchema({
    businessLayers: {
      id: Number,
      layer: String,
      values: Object
    }
  }
);

// This is the function that returns the middlware:
function enforceSchema(dbSchema) {
  return {
    stack: "dbcore",
    name: "SchemaEnforcement",
    create (downlevelDatabase) {
      return {
        ...downlevelDatabase, 
        table (tableName) {
          const downlevelTable = downlevelDatabase.table(tableName);
          const tableSchema = dbSchema[tableName];
          if (!tableSchema) return downlevelTable; // No schema for this table.
          return {
            ...downlevelTable,
            mutate: req => {
              if (req.type === "add" || req.type === "put") {
                for (obj of req.values) {
                  validateSchema(tableName, tableSchema, obj);
                }
              }
              return downlevelTable.mutate(req);
            }
          }
        }
      };
    }
  };
}

function validateSchema(tableName, schema, obj) {
  const invalidProp = Object.keys(schema).find(key => 
  {
    const value = obj[key];
    const type = schema[key];
    switch (type) {
      // Handle numbers, strings and booleans specifically:
      case Number: return typeof value !== "number";
      case String: return typeof value !== "string";
      case Boolean: return typeof value !== "boolean";
      // All other types will be supported in the following
      // single line:
      default: return !(value instanceof type); 
    }
  });
  if (invalidProp) {
    // Throw exception to abort the transaction and make the
    // user get a rejected promise:
    throw new TypeError(`Invalid type given for property ${invalidProp} in table ${tableName}. ${schema[invalidProp].name} expected.`);
  }
}