most-couchdb
Version:
most (data streaming) for CouchDB
127 lines (109 loc) • 3.27 kB
JavaScript
// Generated by CoffeeScript 2.4.1
(function() {
var CouchDBWithUpdate, id_of, isDeepStrictEqual, merge_map, update_map;
merge_map = function(doc) {
return Object.assign({}, doc);
};
update_map = function(doc) {
return {
_rev: doc._rev
};
};
id_of = function({_id}) {
return _id;
};
CouchDBWithUpdate = class CouchDBWithUpdate extends require('./db') {
constructor(...args) {
super(...args);
this.count = {
new: 0n,
changed: 0n,
unchanged: 0n
};
}
// Single-record merge / update
// ----------------------------
__merge(doc, data, map) {
var new_doc;
if ((doc != null ? doc._rev : void 0) != null) {
new_doc = Object.assign(map(doc), data);
if (!isDeepStrictEqual(new_doc, doc)) {
this.count.changed++;
return new_doc;
} else {
this.count.unchanged++;
return null;
}
} else {
this.count.new++;
return data;
}
}
async __update(id, data, map) {
var doc, new_doc;
doc = (await this.get(id).catch(function() {
return {};
}));
new_doc = this.__merge(doc, data, map);
if (new_doc != null) {
await this.put(new_doc);
}
}
// `merge`: update the fields indicated by `data` in an existing document indicated by `id`
// The update is only processed if the document would change.
merge(id, data) {
return this.__update(id, data, merge_map);
}
// `update`: replace a document with new content
// The update is only processed if the document would change.
update(data) {
return this.__update(id_of(data), data, update_map);
}
// Bulk update
// -----------
async bulk_get(docs) { // docs is an Array of {id,rev}
var body, results, uri;
uri = new URL('_bulk_get', this.uri + '/');
({body} = (await this.agent.post(uri.toString()).send({docs}).accept('json')));
({results} = body);
return docs = results.map(function({docs}) {
var ref;
return (ref = docs[0].ok) != null ? ref : null;
});
}
async bulk_docs(docs) { // docs is an Array of documents
var body, uri;
uri = new URL('_bulk_docs', this.uri + '/');
({body} = (await this.agent.post(uri.toString()).send({docs}).accept('json')));
return body;
}
async __bulk_update(ids, new_docs, map) {
var changed, docs, results;
docs = (await this.bulk_get(ids.map(function(id) {
return {id};
})));
new_docs = docs.map((doc, i) => {
var data;
data = new_docs[i];
return this.__merge(doc, data, map);
});
changed = new_docs.filter(function(doc) {
return doc != null;
});
if (changed.length > 0) {
results = (await this.bulk_docs(changed));
} else {
results = [];
}
return results;
}
bulk_merge(ids, changes) {
return this.__bulk_update(ids, changes, merge_map);
}
bulk_update(docs) {
return this.__bulk_update(docs.map(id_of), docs, update_map);
}
};
module.exports = CouchDBWithUpdate;
({isDeepStrictEqual} = require('util'));
}).call(this);