首页 > 解决方案 > 确保 Dexie.js 字段中的数据类型

问题描述

我的 React 应用程序中有一个带有“businessLayers”表的 Dexie.js 数据库。我想确保插入该表中的元组的数据类型。我认为 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;

我想让不可能在每个字段上插入无效的数据类型。我还没有找到任何内置的方法来做到这一点。你知道任何?谢谢!

标签: javascriptindexeddbdexie

解决方案


Table.defineClass() 是 Dexie 1.x 中的一个旧功能,仅用于代码完成 - 没有强制执行。该方法应该已被弃用。但是您需要的功能可以使用DBCore中间件或创建/更新挂钩来实现。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.`);
  }
}

推荐阅读