pouchdb-mapreduce-utils
Version:
PouchDB utilities used by pouchdb-mapreduce.
113 lines (102 loc) • 2.5 kB
JavaScript
import { nextTick } from 'pouchdb-utils';
class QueryParseError extends Error {
constructor(message) {
super();
this.status = 400;
this.name = 'query_parse_error';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, QueryParseError);
} catch (e) {}
}
}
class NotFoundError extends Error {
constructor(message) {
super();
this.status = 404;
this.name = 'not_found';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, NotFoundError);
} catch (e) {}
}
}
class BuiltInError extends Error {
constructor(message) {
super();
this.status = 500;
this.name = 'invalid_value';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, BuiltInError);
} catch (e) {}
}
}
function promisedCallback(promise, callback) {
if (callback) {
promise.then(function (res) {
nextTick(function () {
callback(null, res);
});
}, function (reason) {
nextTick(function () {
callback(reason);
});
});
}
return promise;
}
function callbackify(fun) {
return function (...args) {
var cb = args.pop();
var promise = fun.apply(this, args);
if (typeof cb === 'function') {
promisedCallback(promise, cb);
}
return promise;
};
}
// Promise finally util similar to Q.finally
function fin(promise, finalPromiseFactory) {
return promise.then(function (res) {
return finalPromiseFactory().then(function () {
return res;
});
}, function (reason) {
return finalPromiseFactory().then(function () {
throw reason;
});
});
}
function sequentialize(queue, promiseFactory) {
return function () {
var args = arguments;
var that = this;
return queue.add(function () {
return promiseFactory.apply(that, args);
});
};
}
// uniq an array of strings, order not guaranteed
// similar to underscore/lodash _.uniq
function uniq(arr) {
var theSet = new Set(arr);
var result = new Array(theSet.size);
var index = -1;
theSet.forEach(function (value) {
result[++index] = value;
});
return result;
}
function mapToKeysArray(map) {
var result = new Array(map.size);
var index = -1;
map.forEach(function (value, key) {
result[++index] = key;
});
return result;
}
export { uniq, sequentialize, fin, callbackify, promisedCallback, mapToKeysArray, QueryParseError, NotFoundError, BuiltInError };