Skip to content

Instantly share code, notes, and snippets.

@rblalock
Created April 22, 2014 20:59
Show Gist options
  • Save rblalock/11194110 to your computer and use it in GitHub Desktop.
Save rblalock/11194110 to your computer and use it in GitHub Desktop.
/**
* Caching functions class
* @class Cache
*/
var Moment = require("alloy/moment");
var directory;
exports.valid = function (_url) {
var fileName = _url.replace(/[^\w\d]/g, "");
var file = Ti.Filesystem.getFile(directory.resolve(), fileName);
if (file.exists()) {
return true;
} else {
return false;
}
};
exports.read = function (_url) {
var fileName = _url.replace(/[^\w\d]/g, "");
var file = Ti.Filesystem.getFile(directory.resolve(), fileName);
if (file.exists()) {
var data = file.read();
} else {
return false;
}
return JSON.parse(data);
};
exports.write = function (_url, _data) {
var fileName = _url.replace(/[^\w\d]/g, "");
var file = Ti.Filesystem.getFile(directory.resolve(), fileName);
if (file.write(JSON.stringify(_data)) === false) {
Ti.API.error("Could not write to local cache");
}
file = null;
};
exports.clear = function () {
if (directory.exists() && directory.isDirectory()) {
directory.deleteDirectory(true);
}
};
exports.stage = function () {
var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, "httpCache");
if (!dir.exists()) {
dir.createDirectory();
}
directory = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, "httpCache");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment