javascript - 确保 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;
我想让不可能在每个字段上插入无效的数据类型。我还没有找到任何内置的方法来做到这一点。你知道任何?谢谢!
解决方案
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.`);
}
}
推荐阅读
- chart.js - 折线图末尾的范围
- c# - 将类的属性绑定到 WPF 按钮
- python - Bluez 个人资料注册
- delphi - Delphi 10.2 IDE 在调试时无法从“附加到进程”中看到系统进程。-是的,我正在“以管理员身份运行”
- python - 运行一个从.txt打印行的python程序,得到一个随机的无打印
- python - 在 train_test_split sklearn 中随机定义训练大小
- c++ - 结构内的C ++可变数组长度
- sql - Redshift:Javascript 时间格式 Varchar 字段的日期比较
- c++ - HDF5 简单读取数据集失败
- javascript - 显示一定时间后如何隐藏或删除消息?