Przeglądaj źródła

feat(medata): async cloud and indexedDB save Metadata Data

Lind 4 lat temu
rodzic
commit
58eb9d87b5

+ 1 - 1
config/config.ts

@@ -51,7 +51,7 @@ export default defineConfig({
   },
   lessLoader: {
     modifyVars: {
-      'root-entry-name': 'default',
+      'root-entry-name': 'default', // 解决antd 4.17.0-alpha.9 bug 官方发布正式版后可尝试移除
     },
   },
   // Fast Refresh 热更新

+ 2 - 2
src/db.ts

@@ -24,9 +24,9 @@ class DexieDB {
   updateSchema = async (extendedSchema: Record<string, string | null>) => {
     // 打开后才能获取正确的版本号
     // console.log(database)
-    this.getDB().close();
+    await this.getDB().close();
     // 关闭后才可以更改表结构
-    this.getDB()
+    await this.getDB()
       .version(this.db.verno + 1)
       .stores(extendedSchema);
     return this.getDB().open();

+ 10 - 0
src/pages/device/Product/Detail/Metadata/Base/Edit/index.tsx

@@ -36,12 +36,16 @@ import ConfigParam from '@/components/Metadata/ConfigParam';
 import { useIntl } from '@@/plugin-locale/localeExports';
 import { lastValueFrom } from 'rxjs';
 import type { DeviceMetadata } from '@/pages/device/Product/typings';
+import SystemConst from '@/utils/const';
+import DB from '@/db';
+import { useParams } from 'umi';
 
 const Edit = () => {
   const form = createForm({
     initialValues: MetadataModel.item as Record<string, unknown>,
   });
 
+  const param = useParams<{ id: string }>();
   const SchemaField = createSchemaField({
     components: {
       FormItem,
@@ -471,13 +475,19 @@ const Edit = () => {
     // todo 考虑优化
     if (index > -1) {
       config[index] = params;
+      DB.getDB().table(`${param.id}-${type}`).update(params.id, params);
     } else {
       config.push(params);
+      DB.getDB().table(`${param.id}-${type}`).add(params, params.id);
     }
+    // 保存到服务器
     product.metadata = JSON.stringify(metadata);
     const result = await service.saveProduct(product);
     if (result.status === 200) {
       message.success('操作成功!');
+      MetadataModel.edit = false;
+      MetadataModel.item = {};
+      Store.set(SystemConst.REFRESH_METADATA_TABLE, true);
     } else {
       message.error('操作失败!');
     }

+ 10 - 0
src/pages/device/Product/Detail/Metadata/Base/index.tsx

@@ -10,6 +10,8 @@ import { EditOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
 import Edit from '@/pages/device/Product/Detail/Metadata/Base/Edit';
 import { observer } from '@formily/react';
 import MetadataModel from '@/pages/device/Product/Detail/Metadata/Base/model';
+import { Store } from 'jetlinks-store';
+import SystemConst from '@/utils/const';
 
 interface Props {
   type: MetadataType;
@@ -62,6 +64,14 @@ const BaseMetadata = observer((props: Props) => {
     initData().then(() => setLoading(false));
   }, [initData]);
 
+  useEffect(() => {
+    const subscription = Store.subscribe(SystemConst.REFRESH_METADATA_TABLE, async (flag) => {
+      if (flag) {
+        await initData();
+      }
+    });
+    return () => subscription.unsubscribe();
+  }, []);
   return (
     <>
       <ProTable

+ 43 - 33
src/pages/device/Product/Detail/index.tsx

@@ -25,45 +25,55 @@ const ProductDetail = observer(() => {
         // 数据库存储 按设备名称-物模型类别存储  如:yanshi-tags
         const metadata: DeviceMetadata = JSON.parse(data.metadata);
 
-        DB.updateSchema({
-          [`${param.id}-events`]: 'id,name',
-          [`${param.id}-properties`]: 'id,name',
-          [`${param.id}-functions`]: 'id,name',
-          [`${param.id}-tags`]: 'id,name',
-        })
-          .then(() => {
-            /// 应该先判断是否存在数据
-            const EventTable = DB.getDB().table(`${param.id}-events`);
-            EventTable.clear().then(() => {
-              EventTable.bulkAdd(metadata.events || []);
-            });
-            const PropertyTable = DB.getDB().table(`${param.id}-properties`);
-            PropertyTable.clear().then(() => {
-              PropertyTable.bulkAdd(metadata.properties || []);
-            });
-            const FunctionTable = DB.getDB().table(`${param.id}-functions`);
-            FunctionTable.clear().then(() => {
-              FunctionTable.bulkAdd(metadata.functions || []);
-            });
-            const TagTable = DB.getDB().table(`${param.id}-tags`);
-            TagTable.clear().then(() => {
-              TagTable.bulkAdd(metadata.tags || []);
-            });
+        const schema = {
+          [`${param.id}-functions`]: null,
+          [`${param.id}-tags`]: null,
+          [`${param.id}-events`]: null,
+          [`${param.id}-properties`]: null,
+        };
+        // return 表存在未清除完的情况。所以加载前再清除一次。 考虑优化
+        DB.updateSchema(schema).then(() => {
+          DB.updateSchema({
+            [`${param.id}-events`]: 'id',
+            [`${param.id}-properties`]: 'id',
+            [`${param.id}-functions`]: 'id',
+            [`${param.id}-tags`]: 'id',
           })
-          .catch((error) => {
-            console.error(error);
-            throw new Error('IndexDB add Data Error');
-          });
+            .then(() => {
+              /// 应该先判断是否存在数据
+              const EventTable = DB.getDB().table(`${param.id}-events`);
+              EventTable.clear().then(() => {
+                EventTable.bulkAdd(metadata.events || []);
+              });
+              const PropertyTable = DB.getDB().table(`${param.id}-properties`);
+              PropertyTable.clear().then(() => {
+                PropertyTable.bulkAdd(metadata.properties || []);
+              });
+              const FunctionTable = DB.getDB().table(`${param.id}-functions`);
+              FunctionTable.clear().then(() => {
+                FunctionTable.bulkAdd(metadata.functions || []);
+              });
+              const TagTable = DB.getDB().table(`${param.id}-tags`);
+              TagTable.clear().then(() => {
+                TagTable.bulkAdd(metadata.tags || []);
+              });
+            })
+            .catch((error) => {
+              console.error(error);
+              throw new Error('IndexDB add Data Error');
+            });
+        });
       });
     }
+
     return () => {
-      // 删除表是把index 设置为空
-      DB.updateSchema({
-        [`${param.id}-events`]: null,
-        [`${param.id}-properties`]: null,
+      const schema = {
         [`${param.id}-functions`]: null,
         [`${param.id}-tags`]: null,
-      });
+        [`${param.id}-events`]: null,
+        [`${param.id}-properties`]: null,
+      };
+      DB.updateSchema(schema);
     };
   }, [param.id]);
   return (

+ 4 - 0
src/utils/const.ts

@@ -16,6 +16,10 @@ class SystemConst {
   static GLOBAL_WEBSOCKET = 'GLOBAL-WEBSOCKET';
 
   static BIND_USER_STATE = 'false';
+
+  static REFRESH_METADATA = 'refresh_metadata';
+
+  static REFRESH_METADATA_TABLE = 'refresh_metadata_table';
 }
 
 export default SystemConst;