数据.数据历史

12003

项目简介

此章节为JianghuJS 中级advances模板项目中数据历史模块, 介绍以数据行维度记录数据的变更历史,主要用做数据恢复&数据备份

功能使用

概览

WechatIMG101.png

初始化sql

数据历史表_record_history

  1. CREATE TABLE `_record_history` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `table` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '表',
  4. `recordId` int(11) DEFAULT NULL COMMENT '数据在table中的主键id; recordContent.id',
  5. `recordContent` text COLLATE utf8mb4_bin NOT NULL COMMENT '数据JSON',
  6. `packageContent` text COLLATE utf8mb4_bin NOT NULL COMMENT '当时请求的 package JSON',
  7. `operation` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '操作; jhInsert, jhUpdate, jhDelete jhRestore',
  8. `operationByUserId` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '操作者userId; recordContent.operationByUserId',
  9. `operationByUser` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '操作者用户名; recordContent.operationByUser',
  10. `operationAt` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '操作时间; recordContent.operationAt; E.g: 2021-05-28T10:24:54+08:00 ',
  11. PRIMARY KEY (`id`),
  12. KEY `index_record_id` (`recordId`),
  13. KEY `index_table_action` (`table`,`operation`)
  14. ) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='数据历史表';

搜索

后端处理

点击搜索,数据从后端返回全部数据,前端页面完成数据分页

WechatIMG102.png

  • 搜索条件配置

    • 搜索数据表配置

      1. // 可操作数据表, 如有需要手动添加即可
      2. constantObj: {
      3. table: ["_user"],
      4. }
    • 搜索数据类型配置

      1. // 可操作数据类型
      2. constantObj: {
      3. dataType: [
      4. {"value": "onUse", "text": "使用中的数据"},
      5. {"value": "deleted", "text": "已删除的数据"},
      6. ],
      7. }

前端处理

搜索框内数据需要搜索的关键字,前端直接在已有的数据中搜索,不会发起http请求

WechatIMG103.png

数据还原

用于恢复修改的数据, 操作恢复后,数据将恢复到当前数据状态

WechatIMG106.png

创建recordHistory

  1. const operation = 'jhRestore';
  2. const operationAt = dayjs().format();
  3. const operationByUserId = userId;
  4. const operationByUser = username;
  5. const newData = { ...record, operation, operationAt, operationByUserId, operationByUser };
  6. await trx('_record_history').insert({
  7. table, recordId: newData.id, recordContent: JSON.stringify(newData),
  8. packageContent: '{}',
  9. operation, operationAt, operationByUserId, operationByUser,
  10. });

恢复数据

  1. const recordListTemp = await trx(table).where({ id: recordId }).select();
  2. if (recordListTemp.length > 0) {
  3. await trx(table).where({ id: recordId }).update(newData);
  4. } else {
  5. await trx(table).insert(newData);
  6. }