redgeoff / couchdb-howler

Use web sockets to subscribe to CouchDB global changes
MIT License
36 stars 1 forks source link

[Feature request] - Add options to `client` #112

Closed hadrien-toma closed 4 years ago

hadrien-toma commented 4 years ago

Context

I used to apply the following PouchDB pattern and I would be happy to have an equivalent with an instance of the couchdb-howler client.

From what I understand, the actual couchdb-howler client is able to receive changes from a database but it can not:

  1. Get changes of a database, based on a selector, since 0 and get last_seq in response (one shot)
  2. Listen to changes of the previous database, based on the previous selector, since last_seq (live)

PouchDB pattern

So the idea is to first get all the changes related to a selector, then get back the last_seq fetched by this selector and use it to listen lively, since last_seq, changes matching the selector. This way, we can build a sync reduction of the matched documents, ready to use for the UI part.

In the following example, the database name and selector are not really important, they are only used to show how the logic works.

<html>
    <head>
        <script src="http://cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
        <script>
            window.databaseOptions = { name: 'http://localhost:5000/menu-default', auth: { username: 'cloud', password: 'cloud' } };
            window.selector = { "$and": [{ "$or": [{ "pid": { "$eq": "projects-com-gpio-configs" } }, { "pid": { "$eq": "projects-com-gpio-executions" } }] }] };
            window.database = new PouchDB(window.databaseOptions.name, { ...window.databaseOptions });
            window.database.changes({ include_docs: true, selector: window.selector, since: 0 })
                .on('change', (change) => { console.log('since0', { change }) })
                .on('complete', (completeInfo) => {
                    console.log('since0', { completeInfo })
                    window.database.changes({ include_docs: true, live: true, since: completeInfo.last_seq, selector: window.selector, })
                        .on('change', (change) => { console.log('liveSinceLastSeq', { change }) })
                        .on('complete', (completeInfo) => { console.log('liveSinceLastSeq', { completeInfo }) })
                        .on('error', (error) => { console.log('liveSinceLastSeq', { error }) })
                })
                .on('error', (error) => { console.log('since0', { error }) })
        </script>
    </head>
    <body></body>
</html>

Do you think it is something implementable? :crossed_fingers:

redgeoff commented 4 years ago

couchdb-howler is used to listen to whether a database has changed. You can then use Slouch (or nano) to retrieve all the specific changes.

hadrien-toma commented 4 years ago

Nice, thank you for your answer, Slouch seems really interesting.