Giter Club home page Giter Club logo

worker-pouch's Introduction

worker-pouch Build Status

// This pouch is powered by Workers!
var db = new PouchDB('mydb', {adapter: 'worker'});

Adapter plugin to use PouchDB over Web Workers and Service Workers. Transparently proxies all PouchDB API requests to the worker, so that the most expensive database operations are run in a separate thread.

Basically, worker-pouch allows you use the PouchDB API like you normally would, but your UI will suffer fewer hiccups, because any blocking operations (such as IndexedDB or checksumming) are run inside of the worker.

The worker-pouch adapter passes the full PouchDB test suite. It requires PouchDB 5.0.0+.

Topics

Install

$ npm install worker-pouch

Usage

This plugin has two modes:

  • Easy Mode, for Web Workers, supporting Chrome and Firefox, with a fallback for other browsers, and
  • Custom Mode, potentially supporting more browsers, for Service Workers and allowing you to use your own Web Worker.

In Easy Mode, you don't need to set up the worker yourself, because the script is loaded in a Blob URL. Whereas in Custom Mode, you must manage the Web Worker or Service Worker yourself.

Easy Mode

You can do Easy Mode either with prebuilt JavaScript or via Browserify/Webpack.

Setup via prebuilt JavaScript

The client JS file is available at node_modules/worker-pouch/dist/pouchdb.worker-pouch.js. Or you can just download it from Github above (in which case, it will be available as window.workerPouch).

Then include it in your HTML, after PouchDB:

<script src="pouchdb.js"></script>
<script src="pouchdb.worker-pouch.js"></script>

Then you can create a worker-powered PouchDB using:

var db = new PouchDB('mydb', {adapter: 'worker'});

Setup via Browserify/Webpack/etc.

The same rules apply, but you have to notify PouchDB of the new adapter:

var PouchDB = require('pouchdb');
PouchDB.adapter('worker', require('worker-pouch'));

Detecting browser support

Unfortunately, creating workers via Blob URLs is not supported in all browsers. In particular, IE, Edge, Safari, and iOS are not supported. Luckily, Firefox and Chrome are the browsers that benefit the most from web workers. There is also an API to detect browser support, which you must use if you would like to support browsers other than Firefox and Chrome.

Custom Mode

In this mode, you manage the Web Worker yourself, and you register the two endpoints so that worker-pouch can communicate with the "backend" and "frontend."

Since this doesn't require Blob URLs, and because you can use custom PouchDB objects, you can potentially support more browsers this way. It's much more flexible.

This mode only supports bundling via Browserify/Webpack/etc. There is no prebuilt option.

To use, you'll need this code on the client side:

// client-side code
var PouchDB = require('pouchdb');
PouchDB.adapter('worker', require('worker-pouch/client'));

var worker = new Worker('worker.js');

var db = new PouchDB('mydb', {
  adapter: 'worker',
  worker: worker
});

Note that you create the PouchDB object passing in both adapter: 'worker' and worker, which points to your Worker object.

Then you include this code on the worker side:

// worker-side code
var registerWorkerPouch = require('worker-pouch/worker');
var PouchDB = require('pouchdb');

// attach to global `self` object
registerWorkerPouch(self, PouchDB);

If you would like to customize how PouchDB is created inside of the worker, then you can also pass in a custom PouchDB factory function, which is a function that takes an options object (e.g. {name: 'mydb', auto_compaction: true}) and returns a PouchDB object.

This is useful in cases where PouchDB's IndexedDB adapter doesn't work inside of a worker (such as Safari), so for instance you can have the pouchCreator function return an in-memory PouchDB object.

Here's an example:

var PouchDB = require('pouchdb');
require('pouchdb/extras/memory');
function pouchCreator(opts) {
  opts.adapter = 'memory'; // force in-memory mode
  return new PouchDB(opts);
}

var registerWorkerPouch = require('worker-pouch/worker');
registerWorkerPouch(self, pouchCreator);

The PouchDB worker code will listen for messages from the client side, but should ignore any non-worker-pouch messages, so you are free to still use worker.postMessage() as desired.

Service Workers

Communicating with a Service Worker is the same as with a Web Worker. However, you have to wait for the Service Worker to install and start controlling the page. Here's an example:

navigator.serviceWorker.register('sw.js', {
      scope: './'
    }).then(function () {
      if (navigator.serviceWorker.controller) {
        // already active and controlling this page
        return navigator.serviceWorker;
      }
      // wait for a new service worker to control this page
      return new Promise(function (resolve) {
        function onControllerChange() {
          navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange);
          resolve(navigator.serviceWorker);
        }
        navigator.serviceWorker.addEventListener('controllerchange', onControllerChange);
      });
    }).then(function (serviceWorker) { // the worker is ready
      db = new PouchDB('testdb', {
        adapter: 'worker',
        worker: function() {
          return serviceWorker;
        }
      });
      return db;
    }).catch(console.log.bind(console));
  });

Then inside your Service Worker:

// worker-side code
var registerWorkerPouch = require('worker-pouch/worker');
var PouchDB = require('pouchdb');

// attach to global `self` object
registerWorkerPouch(self, PouchDB);

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim()); // activate right now
});

Performance benefits of worker-pouch

These numbers were recorded using this site. The test involved inserting 10000 PouchDB documents, and was run on a 2013 MacBook Air. Browser data was deleted between each test.

Time (ms) Blocked the DOM?
Chrome 48
   put() - normal 50070 No
   put() - worker 56993 No
   bulkDocs() - normal 2740 Yes
   bulkDocs() - worker 3454 No
Firefox 43
   put() - normal 39595 No
   put() - worker 41425 No
   bulkDocs() - normal 1027 Yes
   bulkDocs() - worker 1130 No

Basic takeaway: put()s avoid DOM-blocking (due to using many smaller transactions), but are much slower than bulkDocs(). With worker-pouch, though, you can get nearly all the speed benefit of bulkDocs() without blocking the DOM.

(Note that by "blocked the DOM," I mean froze the animated GIF for a significant amount of time - at least a half-second. A single dropped frame was not penalized. Try the test yourself, and you'll see the difference is pretty stark.)

Fallback for unsupported browsers

In Easy Mode, this plugin doesn't support all browsers. So it provides a special API to dianogose whether or not the current browser supports worker-pouch. Here's how you can use it:

var workerPouch = require('worker-pouch');

workerPouch.isSupportedBrowser().then(function (supported) {
  var db;
  if (supported) {
    db = new PouchDB('mydb', {adapter: 'worker'});
  } else { // fall back to a normal PouchDB
  db = new PouchDB('mydb');
  }
}).catch(console.log.bind(console)); // shouldn't throw an error

The isSupportedBrowser() API returns a Promise for a boolean, which will be true if the browser is supported and false otherwise.

If you are using this method to return the PouchDB object itself from a Promise, be sure to wrap it in an object, to avoid "circular promise" errors:

var workerPouch = require('worker-pouch');

workerPouch.isSupportedBrowser().then(function (supported) {
  if (supported) {
    return {db: new PouchDB('mydb', {adapter: 'worker'})};
  } else { // fall back to a normal PouchDB
  return {db: new PouchDB('mydb')};
  }
}).then(function (dbWrapper) {
  var db = dbWrapper.db; // now I have a PouchDB
}).catch(console.log.bind(console)); // shouldn't throw an error

Debugging

worker-pouch uses debug for logging. So in the browser, you can enable debugging by using PouchDB's logger:

PouchDB.debug.enable('pouchdb:worker:*');

FAQs

Wait, doesn't PouchDB already work in a Web Worker or Service Worker?

Yes, you can use pure PouchDB inside of a Web Worker or Service Worker. But the point of this plugin is to let you use PouchDB from outside a Web Worker or Service Worker, and then have it transparently proxy to another PouchDB that is isolated in a Web Worker or Service Worker.

What browsers are supported?

Only those browsers that 1) Allow service workers or 2) Allow blob URLs for Web Worker scripts and allow IndexedDB inside of a Web Worker. Today, that means Chrome and Firefox.

Can I use it with other plugins?

Not right now, although map/reduce is supported.

Don't I pay a heavy cost of structured cloning due to worker messages?

Yes, but apparently this cost is less than that of IndexedDB, because the DOM is significanty less blocked when using worker-pouch. Another thing to keep in mind is that PouchDB's internal document representation in IndexedDB is more complex than the PouchDB documents you insert. So you clone a small PouchDB object to send it to the worker, and then inside the worker it's exploded into a more complex IndexedDB object. IndexedDB itself has to clone as well, but the more complex cloning is done inside the worker.

Does replication occur inside the worker?

It's a bit subtle. The answer is yes, if you do this:

var local = new PouchDB('local', {adapter: 'worker'});
local.replicate.to('http://example.com/db');

However, the answer is no if you do:

var local = new PouchDB('local', {adapter: 'worker'});
var remote = new PouchDB('http://example.com/db');
local.replicate.to(remote);

The reason is that when you create a remote PouchDB using new PouchDB('http://example.com/db'), then that runs inside the UI thread. However, when you .replicate.to('http://example.com/db'), then that string is passed ver-batim to the worker thread, where worker-pouch becomes responsible for creating the remote PouchDB. Hence replication will occur inside of the worker thread.

In general, if you are very concerned about performance implications of what runs inside of the woker vs what runs outside of the worker, you are encouraged to not use worker-pouch and to instead just run PouchDB inside a worker and handle message-passing yourself (might I recommend promise-worker?). This is the only way to really ensure that all PouchDB operations are isolated to the worker.

Changelog

  • 1.1.0
    • Adds the Custom Mode API
  • 1.0.0
    • Initial release

Building

npm install
npm run build

Your plugin is now located at dist/pouchdb.worker-pouch.js and dist/pouchdb.worker-pouch.min.js and is ready for distribution.

Testing

In the browser

Run npm run dev and then point your favorite browser to http://127.0.0.1:8000/test/index.html.

The query param ?grep=mysearch will search for tests matching mysearch.

Automated browser tests

You can run e.g.

CLIENT=selenium:firefox npm test
CLIENT=selenium:phantomjs npm test

This will run the tests automatically and the process will exit with a 0 or a 1 when it's done. Firefox uses IndexedDB, and PhantomJS uses WebSQL.

Running the custom-api tests

Run:

npm run test-custom

Or to debug:

npm run test-custom-local

worker-pouch's People

Contributors

garethbowen avatar jkleinsc avatar nolanlawson avatar reda-alaoui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

worker-pouch's Issues

Error with Cordova.

Hello, when trying to install worker pouch on Android Cordova / Ionic, I encounter this error.
Is there a way to install it on this platform ?


:processArmv7DebugResources      Unable to add 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\assets\armv7\debug\www\lib\worker-pouch\node_modules\pouchdb
\node_modules\level-sublevel\node_modules\levelup\node_modules\semver\semver.browser.js.gz': file already in archive (try '-u'?)
 FAILED
ERROR: unable to process assets while packaging 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\res\resources-armv7-debug.ap_'
ERROR: packaging of 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\res\resources-armv7-debug.ap_' failed

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':processArmv7DebugResources'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
        C:\Program Files\AndroidStudio\sdk\build-tools\23.0.1\aapt.exe package -f --no-crunch -I C:\Program Files\AndroidStudio\sdk\platforms\android-22\android.jar -M C:\Us
ers\User\Dev\MyIonicApp\platforms\android\build\intermediates\manifests\full\armv7\debug\AndroidManifest.xml -S C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediate
s\res\armv7\debug -A C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\assets\armv7\debug -m -J C:\Users\User\Dev\MyIonicApp\platforms\android\build\generated\s
ource\r\armv7\debug -F C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\res\resources-armv7-debug.ap_ --debug-mode --custom-package net.myapp.app -0 apk
--output-text-symbols C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\symbols\armv7\debug
Error Code:
        1
Output:
              Unable to add 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\assets\armv7\debug\www\lib\worker-pouch\node_modules\pouchdb\node_modules\level
-sublevel\node_modules\levelup\node_modules\semver\semver.browser.js.gz': file already in archive (try '-u'?)
        ERROR: unable to process assets while packaging 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\res\resources-armv7-debug.ap_'
        ERROR: packaging of 'C:\Users\User\Dev\MyIonicApp\platforms\android\build\intermediates\res\resources-armv7-debug.ap_' failed


* Try:

BUILD FAILED

Total time: 38.086 secs
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

C:\Users\User\Dev\MyIonicApp\platforms\android\cordova\node_modules\q\q.js:126
                    throw e;
                          ^
Error code 1 for command: cmd with args: /s /c "C:\Users\User\Dev\MyIonicApp\platforms\android\gradlew cdvBuildDebug -b C:\Users\User\Dev\MyIonicApp\platforms\android\build.grad
le -PcdvBuildArch=arm -Dorg.gradle.daemon=true"

Promises not catched with Angular 6 & zonejs

So I got an Angular 6 application w/ [email protected] running in Chrome 67.

When I run the following code I get an error using worker-pouch

db.get('invalidbla').catch(e => console.log('catched'))

I get the following console output

> catched
> core.js:1624 ERROR Error: Uncaught (in promise): Object: {"error":"not_found","name":"not_found","reason":"missing","message":"missing","status":404}
    at resolvePromise (zone.js:814)
    at zone.js:724
    at zone.js:740
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
    at Object.onInvoke (core.js:3757)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
    at zone.js:872
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3748)
defaultErrorLogger @ core.js:1624
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1670
next @ core.js:4252
schedulerFn @ core.js:3488
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:195
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:133
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3480
(anonymous) @ core.js:3779
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3716
onHandleError @ core.js:3779
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:392
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:677
api.microtaskDrainDone @ zone.js:686
drainMicroTaskQueue @ zone.js:602
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566

When I run in with adapter: idb the output is just catched.

I am unsure how to continue debugging this though.

console is not defined

Using worker-pouch I'm getting random pouch calls failing with "console is not defined".

eed4b2e8-1607-11e6-8b3b-f6cd9b3d7bf7

This happens on Chrome v30 which is what the webview for android 4.4.2 is locked to. I can't reproduce on Firefox or Chrome latest. I think this is due to the console not being defined in web workers in this version of Chrome.

I assume this is due to something in PouchDB logging but it's very difficult to test and debug, so I can't tell for sure.

Maybe the fix is some sort of console polyfill (eg: https://github.com/padolsey/operative/blob/master/src/contexts/BrowserWorker.js#L189) or maybe just a console stub so log messages are ignored.

Race condition on error handling

If I try to get a doc that doesn't exist immediately on page load I get an uncaught exception in promise. If I try to get the same doc after a 1 second delay then the error is handled as expected. If I remove worker-pouch the 404s are handled as expected.

I've done some digging around to try and get more information but unfortunately I haven't gotten far, but here's what I have...

uncaught-exception

doc-not-found

I'm not sure if it's relevant but I use angular-pouchdb.

Let me know if there's anything else I can do to help.

SharedArrayBuffer

Curious, I'm new to workers/SAB, does this seem like something possible that would get over the buffer copying?

If this is doable without too much fuss I'm going to experiment with it and see if I can't get a PR, but figure it's worth seeing if anyone sees any obvious blockers or tricky areas.

replication - option.since type

@nolanlawson: I'm testing the worker adapter, and FYI, the filtered replication from a local PouchDB => remote CouchDB works only if the option.since is an integer (ex: 1442). With the websql adapter it's working if it is a string. (ex : "1442").

I was using string as the remote Cloudant DB use strings....

No remote connection over HTTP?

Hi, I've been trying to setup my PouchDB ,syncing with a remote CouchDB, inside a worker using this plugin.

After some digging around, I found that the function for creating a HTTP connected Pouch inside the worker is actually never called. The makePouchCreator function is always called with an empty options object:

https://github.com/nolanlawson/worker-pouch/blob/master/lib/worker/index.js#L240-L241

var options = {};
var pouchCreator = makePouchCreator(options);

This leads to the createHttpPouch function never being called:

https://github.com/nolanlawson/worker-pouch/blob/master/lib/worker/make-pouch-creator.js#L33-L39

function makePouchCreator(options) {
  if (options.remoteUrl) {
    return createHttpPouch(options);
  }
  if (!options.pouchCreator) {
    return createLocalPouch;
  }

  // …
}

So, as I see it, PouchDB sync with another DB over HTTP doesn't work at all when using worker-pouch.

Or am I missing something?

Add pouchdb-find support

Should be easy by just adding some kind of custom implementation capability like I did for map/reduce.

Error while making a .find query with index created

I have an application which uses worker-pouch
I have an index on a key called "docType", worker-pouch throws an error while calling db.find()

{error: "not_found", name: "not_found", reason: "ddoc _design/idx-f69ab836cb594ee7fe57e44b2d3c4267 …44b2d3c4267, instead found object of type: object", message: "ddoc _design/idx-f69ab836cb594ee7fe57e44b2d3c4267 …44b2d3c4267, instead found object of type: object", status: 404}

Actually support ServiceWorker

This lib doesn't support ServiceWorker yet because it needs to implement the SW-specific postMessage API using MessageChannels (ala promise-worker).

Unable to get the changes - worker and db.changes

When testing the db.changes with the worker adapter :

I encounter a strange behavior with my chrome desktop and the chrome Android in regard to the paste.pouchdb.com.

When using the test script on this site (available here) : http://paste.pouchdb.com/paste/1df1i5
I can see in the console logs that the db.changes listener is working.

image

When I use this code on my Ionic APP client The db.changes listener is not working.

Do you know what is going on, and why I encounter this issue ? ?

Regards,
Ron

Replication issue with the worker. (remoteDB cloudant)

Here is my test code.

When selecting the adapter 'worker' it doesn't work.
When selecting the adapter 'websql' it works properly !

creation LocalDB & RemoteDB ==> put a Doc in LocalDB ==> replicate localDB to RemoteDB ==> put a Doc in RemoteDB ==> replicate remoteDB to localDB ==> fetch RemoteDB docs.

<div>
    <html>

    <head>
        <meta charset="utf-8">
        <title>Angular JS</title>
    </head>

    <body ng-app="myapp">
    <div ng-controller="DemoCtrl as demo">
        <h1>Hello {{demo.name}}</h1>
        <p>ok</p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
    <script src="https://npmcdn.com/pouchdb/dist/pouchdb.js"></script>
    <script src="https://npmcdn.com/worker-pouch/dist/pouchdb.worker-pouch.js"></script>
    <script src="https://cdn.jsdelivr.net/lodash/3.10.1/lodash.js"></script>

    <script>


        var app = angular.module('myapp', []);

        app.controller('DemoCtrl', function($q) {
            this.name = 'World';
            console.log("GO");

            var self = {

                localDB : null,
                remoteDB : null,

                checkWorker : function(){
                    console.log("checkWorker");

                PouchDB.debug.enable('*');
                    var remoteUrl = "https://dscrindeavelfcloestorest:[email protected]/remote-test-db";
                    self.remoteDB = new PouchDB(remoteUrl);
                    self.localDB = new PouchDB('localDB', {adapter: 'worker'});
                    var time = (new Date()).getTime();

                    self.localDB.destroy()
                            .then(function(res){
                                console.log("Destroy localDB and recreate it.",res);
                                return new PouchDB('localDB', {adapter: 'worker'});
                            })
                            .then(function(local){
                                console.log("localDB",local);
                                self.localDB = local;
                                return  self.localDB.put({_id: time + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', test: 'yo'});
                            })
                            .then(function (res) {
                                console.log("put local",res);
                                console.log("remote _db_name", self.remoteDB._db_name);
                                return self.remoteDB.info();
                            })
                            .then(function (res) {
                                console.log("remote info",res);
                                return self.localDB.replicate.to(remoteUrl, {retry:true});
                                //return self.replicate(self.localDB,remoteUrl,{retry:true});  ==> replicate function with more logs.
                            })
                            .then(function (res) {
                                console.log("replicate remote",res);
                                return self.remoteDB.info();
                            })
                            .then(function (info) {
                                console.log('remote database info after replicate local To remoteDB ', info);
                            })
                            .then(function () {
                                self.remoteDB.put({_id: time+'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', test: 'yo'});
                            })
                            .then(function () {
                                return self.localDB.replicate.from(self.remoteDB, {retry:true});
                            })
                            .then(function () {
                                return self.remoteDB.info();
                            })
                            .then(function (info) {
                                console.log('remote database info after replicate remote to Local', info);
                            })
                            .then(function () {
                                return self.remoteDB.allDocs({include_docs:true});
                            })
                            .then(function (docs) {
                                console.log('SUCCESS !!!!!!!!!!! remoteDB database docs', docs);
                            })
                            .catch(function(e){
                                console.error("Error : ", e);
                            });
                },

                replicate : function(dba, dbb, options){
                    console.info("replicate", dba._db_name, dbb, options);

                    var defer = $q.defer();
                    dba.replicate.to(dbb, options)
                            .on('complete', function (res) {
                                // yay, we're done!
                                console.info("complete",  res, options);
                                if(_.isString(dbb)){
                                    defer.resolve(new PouchDB(dbb).info());
                                }
                                else{
                                    defer.resolve(dbb.info());
                                }
                            })
                            .on('paused', function (info) {
                                // replication was paused, usually because of a lost connection
                                console.info(info, "paused");
                            })
                            .on('active', function (info) {
                                // replication was resumed
                                console.info(info, "active");
                            })
                            .on('change', function (info) {
                                // handle change
                                console.info("change", info);
                            })
                            .on('error', function (err) {
                                // boo, something went wrong!
                                console.error("replicate: ", JSON.stringify(err));
                                setTimeout(function(){
                                    return self.replicate(dba, dbb, options);
                                }, 2000);
                            });

                    return defer.promise;
                },
            };

            //launch the test
            self.checkWorker();

        });

    </script>

    </body>
</div>

Worker-Pouch not working with new pouchdb version 6.0.4

Hi,

I have updated to the latest pouchdb version & noticed that the worker-pouch which I have been using with the old pouchdb version 5.4.5 is not working with this new version.

Wanted to know what might be the problem here & when can this be fixed?

Thanks,
Ajinkya

Error: process not found

I'm getting this error when trying to make index on local pouchdb (idb).

utils.js?3b7b:59 Uncaught (in promise) ReferenceError: process is not defined
    at usedCB (utils.js?3b7b:59)

Highlited function is from utils.js line 59. Any help appreciated.

I'm using pouchdb latest with quasar (vue 3), chrome latest, windows 11.

Typescript + Angular (webpack)

I have an issue with pouch db that causes the UI thread to be sluggish when using put().
I was hoping to use this plugin to fix this.
I had issues make PouchDB work and I hope this isn't the root cause.

  1. in tsconfig.json add "allowSyntheticDefaultImports": true
  2. import PouchDB from "pouchdb";
  3. let db = new PouchDB("db");
    So far the original setup which works on the UI thread.
    Now when doing the following
...
import "worker-pouch";
...
let db= new PouchDB("db", { adapter: "worker" });

I'm getting an error: Invalid Adapter: worker
When using:

var PouchDB = require('pouchdb');
PouchDB.adapter('worker', require('worker-pouch'));

I'm getting an error: PouchDB.adapter is not a function

I've also tried with PouchDB.plugin(require('worker-pouch')) but it didn't work too, something with immutable...

Help would be appreciated, I'm probably missing a simple thing...

example local.replicate.to: "Cannot read property 'to' of undefined"

I am trying the basic replication example, as given in the readme (using browserify, in angular, if that makes any difference):

'use strict'

const PouchDB = require('pouchdb')
const workerPouch = require('worker-pouch')

function DataService ($http, $q, Config) {
  var local = new PouchDB('local', {adapter: 'worker'})
  local.replicate.to('http://localhost:5984/local-test')
...
}

but I am receiving "Cannot read property 'to' of undefined", on the 'replicate' property of local.

Am I missing something about how to set this up?

I am primarily interested in replicating from a remote within the worker, but I figured I should at least get the example working as written.

$ npm list pouchdb worker-pouch
...
├── [email protected]
└── [email protected]

Fix db.type() deprecation warning

We're getting a bunch of this in the browser console...

db.type() is deprecated and will be removed in a future version of PouchDB

This is logged because the adapter doesn't have a _remote property.

This should be fixed to reduce the console spam and also maintain compatibility with future PouchDB releases.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.