VUE - 使用Rxdb存储浏览器数据库

VUE - 使用Rxdb存储浏览器数据库

Rxdb官网:https://rxdb.info/

开发环境:vue2,vuecli4

安装插件:

安装:pouchdb-adapter-idb

如使用 npm 则安装 rxdb,如使用yarn 则使用rxjs。

npm install rxdb --save-dev
yarn add rxjs --save-dev

 在src文件下创建 rxdb-pack 文件夹

创建如下结构

 

 

 

 schemas.js ,创建 demo 文件schema

//node
const schemaDemo = {
  version: 0,
  primaryKey: 'id',
  type: 'object',
  properties: {
    id: {
      type: 'string'
    },
    name: {
      type: 'string'
    },
    updatedAt: {
      type: 'number'
    },
    "_deleted": {
      type: 'boolean',
      default: false
    },
  },
  required: ['id']
};
 
export {
  schemaDemo
}

 

 

 index.js

import {
  createRxDatabase,
  removeRxDatabase
} from 'rxdb';

// because we use the PouchDB RxStorage, we have to add the indexeddb adapter first.
import {
  getRxStoragePouch,
  addPouchPlugin
} from 'rxdb/plugins/pouchdb';
addPouchPlugin(require('pouchdb-adapter-idb'));

import {
  schemaDemo
} from './schemas';


let Database = {};
let dbConfig = {
  name: 'heroesdb',
  storage: getRxStoragePouch('idb')
}

//创建
let createPromise = null;
const create = async () => {
  const database = await createRxDatabase({
    name: dbConfig.name, // <- name
    storage: dbConfig.storage, // <- RxStorage
    password: '%kD8n^%nR3GP9ouc', // <- password (optional)
    multiInstance: true, // <- multiInstance (optional, default: true)
    eventReduce: true // <- eventReduce (optional, default: true)
  });

  //创建表
  await database.addCollections({
    demo: {
      schema: schemaDemo
    }
  });

  return database;
};

// Database.remove = async () => {
//   await removeRxDatabase(dbConfig.name, dbConfig.storage);
// };

//获取
Database.get = async () => {
  if (!createPromise) {
    createPromise = await create();
  }
  return createPromise;
};

export default Database;

 

 

sence.js

import OpeBase from "./base";
import Database from '../index';

class OpsSence extends OpeBase {
  constructor(_myColl) {
    super(_myColl);
    this.myColl = _myColl;
  }

  static async build() {
    let mydb = await Database.get();
    let _myColl = mydb.demo;
    return new OpsSence(_myColl);
  }
}

export default OpsSence;

 

 

 base.js

class OpeBase {

  constructor(_myColl) { this.myColl = _myColl; 
  }

  //批量增加
  bulkInsert = async (arr) => await this.myColl.bulkInsert(arr);

  //新增/修改
  atomicUpsert = async (obj) => await this.myColl.atomicUpsert(obj);

  //删除
  removeOne = async (id) => await this.myColl.findOne(id).remove();

  //删除
  removeArr = async (ids) => await this.myColl.findByIds(ids).remove();

  //清理
  clear = async () => await this.myColl.find().remove();

  //查找
  findOne = async (id) => await this.myColl.findOne(id);


  //查找 
  findArr = async (ids) => await this.myColl.findByIds(ids);

  //查找
  findAll = async () => await this.myColl.find().exec();
}
export default OpeBase;

 

 

synchro.js

数据同步,跟据实际情况调整

import {
  replicateRxCollection
} from 'rxdb/plugins/replication';

import {
  api_getNodeList
} from '@/api/node';

let synchronization = {};

let replicationState = {}; //状态集维护

// 初始化状态
let initone = async (rxCollection) => {
  let rState = await replicateRxCollection({
    collection: rxCollection,
    replicationIdentifier: 'my-custom-rest-replication',
    live: true,
    liveInterval: 30000,
    //   retryTime: number,
    pull: {
      async handler(latestPullDocument) {
        const limitPerPull = 100;
        const minTimestamp = latestPullDocument ? latestPullDocument.updatedAt : 0;
        const minId = latestPullDocument ? latestPullDocument.Id : 0;
        
        let response = null;
        if (rxCollection.name == "node") {
          let param = {
            // $filter: `updateAt ge ${minTimestamp} and Id gt ${minId}`, // ge:>=  gt:>
            $filter: ` Id lt 10000 `, // ge:>=  gt:>
          }
          response = await api_getNodeList(param);
        }

        if (rxCollection.name == "sence") {
          response = await api_getNodeList(param);
        }
        
        // let documentsFromRemote = response; // await response.json();
        // documentsFromRemote.forEach(t => t.id = t.Id.toString());

        let documentsFromRemote = response.map(t => {
          return {
            id: t.Id.toString(),
            name: t.Name,
            parentId: t.ParentId,
            updatedAt: t.updatedAt,
            "_deleted": false
          }
        });

        
        return {
          documents: documentsFromRemote,
          hasMoreDocuments: documentsFromRemote.length === limitPerPull
        };
      }
    }
  });
  return rState;
};

// 获取状态
synchronization.get = async (collectionName, rxCollection) => {
  if (!replicationState[collectionName]) {
    replicationState[collectionName] = await initone(rxCollection);
  }
  return replicationState[collectionName];
}

//初始化状态
synchronization.initall = async (rxCollectionArrs) => {
  rxCollectionArrs.forEach(async (rxCollection) => {
    replicationState[rxCollection.name] = await initone(rxCollection);
  });
}

synchronization.run = async (collectionName) => {

  let sss = await replicationState[collectionName].run();

}

export default synchronization;

 

 

实例操作: 

    let mydb = await Database.get();

    let demoIns = await mydb.demo.bulkInsert([
      {
        id: "aaaa",
        name: "进坧远在天边aaaaaaaaa",
        updatedAt: Math.round(new Date().getTime() / 1000),
        _deleted: false,
      },
      {
        id: "bbbb",
        name: "节节子子孙孙bbbbbbb",
        updatedAt: Math.round(new Date().getTime() / 1000),
        _deleted: false,
      },
      {
        id: "cccc",
        name: "节点ccccccccccc",
        updatedAt: Math.round(new Date().getTime() / 1000),
        _deleted: false,
      },
    ]);
 
    let sss = mydb.demo.find();

    let vc = await sss.exec(); 

    let cc = await mydb.demo.find().exec(); 
 
如需要同步浏览器数据与服务器数据
在main.js 中的 mounted 同步数据
    let mydb = await Database.get();
    synchronization.initall([mydb.node]);

 

  

参考:https://rxdb.info/

 

posted @ 2022-02-22 10:02  无心々菜  阅读(884)  评论(0编辑  收藏  举报