如何解决确保 Dexie.js 字段中的数据类型
我的 React 应用程序中有一个 Dexie.js 数据库,其中包含表“businessLayers”。我想确保插入该表中的元组的数据类型。我认为 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 中间件或 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.`);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。