HackerNoon.com
Published in

HackerNoon.com

Don’t Just Relax; Slouch: A JS Client for CouchDB that Does the Heavy Lifting

Fault Tolerance

StreamIterators

Example 1 — Sequentially process all docs in a DB

slouch.doc.all('mydb', { include_docs: true })
.each(function (item) {

// If we return a promise then the all() iterator won't move on
// to the next item until the promise resolves. This allows us
// to iterate through a large number of docs without consuming a
// lot of memory. It also allows us to control the flow of the
// docs and process them sequentially so that we don't end up
// thrashing the processor with too many concurrent promises.
return Promise.resolve('foo => ' + item.foo);

}).then(function () {

// Done iterating through all docs

}).catch (function (err) {

// An error occurred

});

Example 2 — Process a max of 5 docs concurrently

var Throttler = require('squadron').Throttler;
var throttler = new Throttler(5);

slouch.doc.all('mydb', { include_docs: true })
.each(function (item) {

return Promise.resolve('foo => ' + item.foo);

}, throttler).then(function () {

// Done iterating through all docs

});

Helper functions

upsert

slouch.doc.upsert('mydb', { _id: '1', foo: 'bar' });

getMergeUpsert

// Create a doc
slouch.doc.create('mydb', { _id: '1', foo: 'bar' })
.then(function (doc) {
// Add the `yar` attr to the doc and ignore any conflicts
return slouch.doc.getMergeUpsert('mydb',
{ _id: '1', yar: 'nar' });
});

Slouch and Beyond

About the Author

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Geoff Cox

A coder with a passion for JS, React, GraphQL, Docker and Serverless