Repository navigation
Expand file tree
/
Copy pathclient.js
More file actions
104 lines (92 loc) · 2.4 KB
/
Copy pathclient.js
File metadata and controls
104 lines (92 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
function Client(settings){
this.dropbox = new Dropbox.Client(settings);
var prefix = "ynab";
this.hasLocalStorageSupport = (function(){
try {
var key = "ynab:localStorage:test";
localStorage.setItem(key, "a");
localStorage.removeItem(key);
return true;
} catch(e) {
return false;
}
})();
this.load = function (path, method){
var deferred = new $.Deferred;
var cached = undefined;//fetchCache(method, path);
if(cached !== undefined) {
setTimeout(function(){
deferred.resolve(cached);
}, 10)
} else {
this.dropbox[method](path, function(error, data) {
if (error) {
deferred.reject(error);
}else{
pushCache(method, path, data);
deferred.resolve(data);
}
});
}
return deferred;
}
this.loadJson = function(path){
return this.load(path, "readFile").then(function(data){
return JSON.parse(data);
});
}
this.readDir = function(path){
return this.load(path, "readdir");
}
this.authenticate = function(){
var deferred = new $.Deferred;
this.dropbox.authenticate(function(error, client) {
if (error) {
deferred.reject(error);
}else{
deferred.resolve(client);
}
});
return deferred;
}
this.flushCache = function() {
if(this.hasLocalStorageSupport) {
Object.keys(localStorage).forEach(function(key){
if(key.indexOf("ynab") === 0) {
localStorage.removeItem(key);
}
});
}
}
var cacheTTL = 5 * 60 * 1000;
function fetchCache(method, path) {
if(this.hasLocalStorageSupport) {
var key = cacheKey(method, path);
var cached = localStorage[key];
if(cached) {
try {
var parsed = JSON.parse(cached);
var expired = now() - (cacheTTL + parsed.timestamp) > 0;
if(expired) {
localStorage.removeItem(key);
return undefined;
} else {
return parsed.data;
}
} catch(e) {}
}
}
return undefined;
}
function now(){
return (new Date).getTime()
}
function pushCache(method, path, value) {
if(this.hasLocalStorageSupport) {
localStorage[cacheKey(method, path)] = JSON.stringify({ data: value, timestamp: now() });
}
}
function cacheKey(method, path) {
return [prefix, method, path].join(":");
}
}