Skip to content

Instantly share code, notes, and snippets.

@fponticelli
Created September 16, 2015 17:19
Show Gist options
  • Save fponticelli/2ef88de57cccdc92c0ef to your computer and use it in GitHub Desktop.
Save fponticelli/2ef88de57cccdc92c0ef to your computer and use it in GitHub Desktop.
Lazy evaluation of remote files
-js bin/lazy.js
-cp src
-lib thx.core
-lib thx.load
-lib thx.http
-lib thx.promise
-lib hxnodejs
-main Main
-D hxnodejs
-cmd node bin/lazy.js
var _ = require('lodash'),
squel = require('squel');
var query = function(options) {
var name = _.kebabCase(options.name);
return squel.select()
.from("SOMEWHERE")
.where("name = ?", name).toString();
}
exports = query;
import js.node.vm.Script;
using thx.promise.Promise;
class Lazy {
static var map : Map<String, Script> = new Map();
public static function load(path : String) : Promise<{} -> String> {
var script = map.get(path);
if(null != script) {
return Promise.value(loadScript(script));
}
return thx.load.Loader.getText(path)
.mapSuccessPromise(function(content) {
var script = new Script(content, {
filename : path,
displayErrors : true
});
map.set(path, script);
return Promise.value(loadScript(script));
});
}
static function loadScript(script : Script) : {} -> String {
var sandbox = createContext();
// TODO manage error handling
script.runInNewContext(sandbox);
return sandbox.exports;
}
static function createContext() {
return {
exports : null,
require : js.Node.require
};
}
}
using thx.promise.Promise;
using thx.Functions;
class Main {
public static function main() {
queryByName("FrancoShouldBeTheKing")
.success.fn(js.Node.console.log(_))
.mapSuccessPromise(function(_)
return queryByName("FrancoIsTheKing"))
.success.fn(js.Node.console.log(_))
.throwFailure();
}
public static function queryByName(name) {
// I use `static .` from the scripts directory to be able to test this
return Lazy.load("http://localhost:8080/f.js")
.mapSuccess(function(f) {
return f({ name : name });
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment