简体   繁体   中英

How can I copy pouchdb 0000003.log file to Ionic 5 and retrieve the data?

My scenario is to use pouch db data in ionic and I successfully added pouch db package to ionic and created a sample and it worked fine. Now I have a scenario I have the below file在此处输入图片说明

000003.log in which I have all the data, but in ionic it is storing in the indexdb so how can I use this 000003.log data and copy it to indexeddb or is there any way copy the contents ?

Below is my app code

import { Injectable } from '@angular/core';
import PouchDB from 'pouchdb';

@Injectable({
providedIn: 'root'
})
export class DataService {

private database: any;
private myNotes: any;

constructor() {
  this.database = new PouchDB('my-notes');
}

public addNote(theNote: string): Promise<string> {
  const promise = this.database
    .put({
      _id: ('note:' + (new Date()).getTime()),
      note: theNote
    })
    .then((result): string => (result.id));

  return (promise);
}

getMyNotes() {
  return new Promise(resolve => {
    let _self = this;
    this.database.allDocs({
      include_docs: true,
      attachments: true
    }).then(function (result) {
      // handle result
      _self.myNotes = result.rows;
      console.log("Results: " + JSON.stringify(_self.myNotes));
      resolve(_self.myNotes);

    }).catch(function (err) {
      console.log(err);
    });
  });
}

How to export/import the existing database in ionic app? Do I have to store in file system or indexeddb?

By default PouchDb will use IndexDb, so its doing it correctly. If you want to change storage you need to setup a different adapter.

I don't see where you set up the options for the local adapter , so I think you are missing the local & adapter setup options to support it

如何在本地和远程使用 Iconic 设置 PouchDb


Now use the correct adapter you want PouchDB here

PouchDb 适配器设置

I've created an Ionic 5/Angular repo that demonstrates how to take a local pouchdb as described in the OP and load it as a default canned database in the app.

https://github.com/RambleOnRose/canned-pouch-db

The hurdles were not huge, but I encountered some problems along the way, mainly some wrangling with respect to pouchdb's es modules and module default exports.

Specifically, the documentation forpouchdb-replication-stream is not helpful for incorporation for Ionic5/Angular. I assumed the import

import ReplicationStream from 'pouchdb-replication-stream';

Would just work, but unfortunately at runtime this dread error would popup

Type Error: Promise is not a constructor

Ouch! That's a show stopper. However I came across the pouchdb-replication-stream issue es modules

Which prompted the solution:

import ReplicationStream from 'pouchdb-replication-stream/dist/pouchdb.replication-stream.min.js';

Anyway the highlights of the repo are 'can-a-pouchdb.js' and 'data.service.ts'.

can-a-pouchdb.js

This script will create a local node pouchdb and then serialize that db to app/assets/db, which is later loaded by the ionic app.

The important bits of code:

 // create some trivial docs
    const docs = [];
    const dt = new Date(2021, 6, 4, 12, 0, 0);
    for (let i = 0; i < 10; i++, dt.setMinutes(dt.getMinutes() + i)) {
      docs[i] = {
        _id: "note:" + dt.getTime(),
        note: `Note number ${i}`,
      };
    }
    // always start clean - remove database dump file
    fs.rmdirSync(dbPath, { recursive: true });

    PouchDB.plugin(replicationStream.plugin);
    PouchDB.adapter(
      "writableStream",
      replicationStream.adapters.writableStream
    );
    const db = new PouchDB(dbName);

    console.log(JSON.stringify(docs));
    await db.bulkDocs(docs);
    //
    // dump db to file.
    //
    fs.mkdirSync(dumpFileFolder, { recursive: true });
    const ws = fs.createWriteStream(dumpFilePath);
    await db.dump(ws);

To recreate the canned database run the following from the CL:

$ node can-a-pouchdb.js

data.service.ts

Here's how the app's pouchdb is hydrated from the canned database. Take note the db is using the memory adapter, because as a demo app not persisting the db is desirable.

public async init(): Promise<void> {
    if (this.db === undefined) {
      PouchDB.plugin(PouchdbAdapterMemory);
      PouchDB.plugin(ReplicationStream.plugin);
      this.db = new PouchDB(DataService.dbName, { adapter: 'memory' });
      // if the db is empty, hydrate it with the canned db assets/db
      const info = await this.db.info();
      if (info.doc_count === 0) {
        //load the asset into a string
        const cannedDbText = await this.http
          .get('/assets/db/mydb.dump.txt', {
            responseType: 'text',
          })
          .toPromise();
        // hydrate the db
        return (this.db as any).load(
          MemoryStream.createReadStream(cannedDbText)
        );
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM