113 lines
2.5 KiB
JavaScript
113 lines
2.5 KiB
JavaScript
import { Set } from 'pouchdb-collections';
|
|
import argsarray from 'argsarray';
|
|
import { nextTick } from 'pouchdb-utils';
|
|
import inherits from 'inherits';
|
|
|
|
function QueryParseError(message) {
|
|
this.status = 400;
|
|
this.name = 'query_parse_error';
|
|
this.message = message;
|
|
this.error = true;
|
|
try {
|
|
Error.captureStackTrace(this, QueryParseError);
|
|
} catch (e) {}
|
|
}
|
|
|
|
inherits(QueryParseError, Error);
|
|
|
|
function NotFoundError(message) {
|
|
this.status = 404;
|
|
this.name = 'not_found';
|
|
this.message = message;
|
|
this.error = true;
|
|
try {
|
|
Error.captureStackTrace(this, NotFoundError);
|
|
} catch (e) {}
|
|
}
|
|
|
|
inherits(NotFoundError, Error);
|
|
|
|
function BuiltInError(message) {
|
|
this.status = 500;
|
|
this.name = 'invalid_value';
|
|
this.message = message;
|
|
this.error = true;
|
|
try {
|
|
Error.captureStackTrace(this, BuiltInError);
|
|
} catch (e) {}
|
|
}
|
|
|
|
inherits(BuiltInError, Error);
|
|
|
|
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 argsarray(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 };
|