Skip to content

Instantly share code, notes, and snippets.

@nlwillia
Last active July 28, 2016 15:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlwillia/70303c2ccdb69ad3661d to your computer and use it in GitHub Desktop.
Save nlwillia/70303c2ccdb69ad3661d to your computer and use it in GitHub Desktop.
SystemJS translate hook that caches transpilation results of sources that haven't changed in IndexedDB storage.
/**
* SystemJS translate hook that caches transpilation results of sources that haven't changed in IndexedDB storage.
* In Chrome dev tools the cache is easily managed under Resources > IndexedDB > jspm
* There's a global dependency on Dexie.js (ex: //npmcdn.com/dexie@1.3.3/dist/dexie.min.js)
* Adapted from https://gist.github.com/ineentho/3ccaaec164e418f685d7
*/
;(function(){
var db = new Dexie("jspm");
db.version(1).stores({ files: "&url,format,hash,contents" });
db.open();
var log = console.log.bind(console);
System.originalTranslate = System.translate;
System.translate = function (load) {
if (!load.metadata.deps) {
load.metadata.deps = []; // avoid https://github.com/systemjs/systemjs/pull/1158
}
function hash(str) {
// Source: http://stackoverflow.com/a/7616484/502126
var hash = 0, i, chr, len
if (str.length === 0) return hash
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0
}
return hash.toString()
}
var file = {url:load.address, hash:hash(load.source)};
var loader = this;
return db.files.where('url').equals(file.url).first().then(function(cached) {
if (!cached || cached.hash != file.hash) {
return System.originalTranslate.apply(loader, [load]).then(function(translated) {
file.format = load.metadata.format;
file.contents = translated;
return (cached ? db.files.delete(file.url) : Promise.resolve())
.then(db.files.add(file))
.then(function() {
return translated;
}).catch(log);
});
} else {
load.metadata.format = cached.format || undefined;
return cached.contents;
}
}).catch(log);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment