node-simple-router
Version:
Yet another minimalistic router for node.js
427 lines (397 loc) • 12 kB
JavaScript
// Generated by CoffeeScript 1.10.0
(function() {
var Deferred, Promise, PromiseA, defer, fireHandlers, fs, fulfill, pad, readDir, reject, resolve, testFunc, thousand_sep,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
resolve = function(promise, x) {
if (promise === x) {
return reject(promise, new TypeError("promise and resolution value can't be the same object"));
}
if ((x != null ? x.constructor.name : void 0) === 'Promise') {
if (x.isPending()) {
return x._dependants.push(promise);
}
if (x.isFulfilled()) {
return fulfill(promise, x.value);
}
if (x.isRejected()) {
return reject(promise, x.reason);
}
}
return fulfill(promise, x);
};
fulfill = function(promise, value) {
if (!promise.isPending()) {
return promise;
}
promise._state = Promise.states.fulfilled;
promise._value = value;
fireHandlers(promise, value);
promise._dependants.forEach(function(dependant) {
return resolve(dependant, value);
});
return promise;
};
reject = function(promise, reason) {
if (!promise.isPending()) {
return promise;
}
promise._state = Promise.states.rejected;
promise._reason = reason;
fireHandlers(promise, reason);
promise._dependants.forEach(function(dependant) {
return reject(dependant, reason);
});
return promise;
};
fireHandlers = function(promise, what) {
var handlers;
switch (promise._state) {
case Promise.states.rejected:
handlers = promise._rejectHandlers;
break;
case Promise.states.fulfilled:
handlers = promise._fulfillHandlers;
break;
default:
return;
}
handlers.forEach(function(handler, index) {
var cascade_promise, e, error, result;
if (promise._handlerCalls[index] !== 0) {
return;
}
promise._handlerCalls[index] += 1;
cascade_promise = promise._retPromises[index];
if ((handler != null ? handler.constructor.name : void 0) === "Function") {
try {
result = handler(what);
if (promise._state === Promise.states.fulfilled) {
return resolve(cascade_promise, result);
} else {
return reject(cascade_promise, result);
}
} catch (error) {
e = error;
return reject(cascade_promise, e);
}
} else {
if (promise._state === Promise.states.fulfilled) {
return resolve(cascade_promise, what);
} else {
return reject(cascade_promise, what);
}
}
});
return promise;
};
Promise = (function() {
"Returns a promise object which complies (really?) with promises A+ spec";
Promise.states = {
pending: 0,
rejected: -1,
fulfilled: 1
};
Object.defineProperties(Promise.prototype, {
value: {
get: function() {
return this._value;
}
},
reason: {
get: function() {
return this._reason;
}
},
state: {
get: function() {
return this._state;
}
}
});
function Promise(_options) {
this._options = _options != null ? _options : {};
this.isResolved = bind(this.isResolved, this);
this.isPending = bind(this.isPending, this);
this.isFulfilled = bind(this.isFulfilled, this);
this.isRejected = bind(this.isRejected, this);
this.fail = bind(this.fail, this);
this.done = bind(this.done, this);
this.then = bind(this.then, this);
Promise.init(this);
}
Promise.init = function(obj) {
obj._state = Promise.states.pending;
obj._fulfillHandlers = [];
obj._rejectHandlers = [];
obj._retPromises = [];
obj._handlerCalls = [];
obj._dependants = [];
return obj;
};
Promise.prototype.then = function(onFulfilled, onRejected) {
var retPromise;
this._fulfillHandlers.push(onFulfilled || null);
this._rejectHandlers.push(onRejected || null);
retPromise = new Promise({
level: this._options.level + 1
});
this._retPromises.push(retPromise);
if (this.isPending()) {
this._handlerCalls.push(0);
} else {
this._handlerCalls.push(1);
if (this.isRejected()) {
reject(retPromise, this._reason);
}
if (this.isFulfilled()) {
if ((onFulfilled != null ? onFulfilled.constructor.name : void 0) === "Function") {
resolve(retPromise, onFulfilled(this._value));
} else {
resolve(retPromise, this._value);
}
}
}
return retPromise;
};
Promise.prototype.done = function(onFulfilled) {
return this.then(onFulfilled, null);
};
Promise.prototype.fail = function(onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.isRejected = function() {
if (this._state === Promise.states.rejected) {
return true;
} else {
return false;
}
};
Promise.prototype.isFulfilled = function() {
if (this._state === Promise.states.fulfilled) {
return true;
} else {
return false;
}
};
Promise.prototype.isPending = function() {
if (this._state === Promise.states.pending) {
return true;
} else {
return false;
}
};
Promise.prototype.isResolved = function() {
return !this.isPending();
};
return Promise;
})();
Deferred = (function() {
"Promise manager object";
function Deferred() {
this.reject = bind(this.reject, this);
this.resolve = bind(this.resolve, this);
this.promise = bind(this.promise, this);
this._promise = new Promise({
level: 0
});
}
Deferred.prototype.promise = function() {
return this._promise;
};
Deferred.prototype.resolve = function(value) {
return setImmediate((function(_this) {
return function() {
if (!_this._promise.isPending()) {
return;
}
return resolve(_this._promise, value);
};
})(this));
};
Deferred.prototype.reject = function(reason) {
return setImmediate((function(_this) {
return function() {
if (!_this._promise.isPending()) {
return;
}
return reject(_this._promise, reason);
};
})(this));
};
return Deferred;
})();
defer = function() {
return new Deferred;
};
if (typeof module !== "undefined" && module !== null) {
module.exports = PromiseA = {
Promise: Promise,
Deferred: Deferred,
defer: defer
};
}
if (!(typeof module !== "undefined" && module !== null ? module.parent : void 0)) {
thousand_sep = function(num, sep) {
var resp;
if (sep == null) {
sep = ",";
}
if (!(num.toString().length > 3)) {
return num.toString();
}
resp = num.toString().split('').reverse().join('').replace(/(\d{3})/g, "$1" + sep).split('').reverse().join('');
if (resp.charAt(0) === sep) {
return resp.slice(1);
} else {
return resp;
}
};
pad = function(stri, quantity, direction, padchar) {
var dif, len, n, padstri;
if (direction == null) {
direction = "r";
}
if (padchar == null) {
padchar = " ";
}
if (stri.constructor.name === "Number") {
stri = stri.toString();
}
len = stri.length;
dif = quantity - len;
if (dif <= 0) {
return stri;
}
padstri = ((function() {
var i, ref, results;
results = [];
for (n = i = 1, ref = dif; 1 <= ref ? i <= ref : i >= ref; n = 1 <= ref ? ++i : --i) {
results.push(padchar);
}
return results;
})()).join('');
if (direction === "r") {
return "" + stri + padstri;
} else {
return "" + padstri + stri;
}
};
testFunc = function() {
var d, p;
d = defer();
setTimeout((function() {
return d.resolve(10);
}), 100);
p = d.promise();
/*
setTimeout (->
console.log "\n"
console.log util.inspect p._fulfillHandlers
console.log util.inspect p._retPromises[0]?._fulfillHandlers
console.log util.inspect p._retPromises[0]?._retPromises[0]?._fulfillHandlers
console.log "\n"), 50
*/
console.log("Running test function");
console.log("---------------------\n");
return p;
};
/*
testFunc()
.then(
(number) ->
console.log "Promise level 0 received number #{number}"
number + 1
(err) =>
console.log "First promise triggered an error:", err.toString()
)
.then(
(number) ->
console.log "Promise level 1 received number #{number}"
number + 1
)
.then(
(number) ->
console.log "Promise level 2 received number #{number}"
number * 3
)
.then(
(resp) ->
console.log "Promise level 3 received number #{resp}"
resp
)
*/
fs = require('fs');
readDir = function() {
var d;
d = defer();
fs.readdir(process.cwd(), function(err, files) {
if (err) {
console.log("ERROR reading directory: ");
} else {
console.log("Current working directory: " + (process.cwd()) + "\n");
}
if (err) {
return d.reject(err);
} else {
return d.resolve(files);
}
});
console.log("Running file system test function");
console.log("---------------------------------\n");
return d.promise();
};
readDir().then(function(files) {
var d, len, p, stats;
len = files.length - 1;
stats = [];
d = defer();
p = d.promise();
files.forEach(function(file, index) {
return fs.stat(file, function(err, stat) {
if (err) {
return d.reject(err);
}
stats[index] = stat;
if (index === len) {
console.log("Retrieved", stats.length, "items.\n");
return d.resolve([files, stats]);
}
});
});
return p;
}, function(err) {
return console.log("ERROR reading current directory: " + err.message);
}).then(function(arrs) {
var file, fileInfo, fileSizes, files, i, index, j, len1, len2, ref, ref1, ref2, stats;
files = arrs[0], stats = arrs[1];
fileSizes = [];
for (index = i = 0, len1 = files.length; i < len1; index = ++i) {
file = files[index];
fileSizes.push({
name: '' + file + (((ref = stats[index]) != null ? ref.isDirectory() : void 0) ? ' [DIR]' : ''),
size: (ref1 = stats[index]) != null ? ref1.size : void 0,
isFile: (ref2 = stats[index]) != null ? ref2.isFile() : void 0
});
}
fileSizes.sort(function(info1, info2) {
return info1.isFile - info2.isFile;
});
for (j = 0, len2 = fileSizes.length; j < len2; j++) {
fileInfo = fileSizes[j];
console.log(pad(fileInfo.name, 40), " --- ", pad(thousand_sep(fileInfo.size), 40, "l"), "bytes.");
}
return fileSizes;
}, function(err) {
return console.log("Something horrible happened while processing file names and stats:", err.message);
}).then(function(fileSizes) {
var info;
info = "\nTotal Size of files in " + (process.cwd()) + ": ";
info += (thousand_sep(fileSizes.reduce((function(acum, fileInfo) {
return acum + (fileInfo.isFile ? fileInfo.size : 0);
}), 0))) + " bytes.\n";
return console.log(info);
}, function(err) {
return console.log("Something horrible happened while processing total files size:", err.message);
});
}
}).call(this);