Created
December 6, 2017 14:33
-
-
Save back2dos/38119fbbab4fbcd178ffc74d0495ae85 to your computer and use it in GitHub Desktop.
Caching client for tink_web.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tink.http.Client; | |
import tink.http.Request; | |
import tink.http.Response; | |
using tink.CoreApi; | |
typedef CachePolicy = OutgoingRequest->IncomingResponse->Future<Noise>; | |
class CachingClient implements tink.http.Client.ClientObject { | |
var actual:Client; | |
var policy:CachePolicy; | |
var cache = new Map<String, Promise<IncomingResponse>>(); | |
static public function ttl(seconds:Float):CachePolicy | |
return | |
function (_, _) return Future.async(function (done) | |
haxe.Timer.delay(done.bind(Noise), Std.int(1000 * seconds)) | |
); | |
public function new(actual, ?policy) { | |
this.actual = actual; | |
this.policy = switch policy { | |
case null: ttl(15); | |
case v: v; | |
} | |
} | |
public function request(req:OutgoingRequest):Promise<IncomingResponse> { | |
return | |
switch req.header.method { | |
case GET | HEAD: | |
var key = req.header.url.toString(); | |
switch cache[key] { | |
case null: | |
var res = actual.request(req); | |
cache[key] = res; | |
function clear() | |
if (cache[key] == res) cache.remove(key); | |
res.handle(function (o) switch o { | |
case Failure(_): clear(); | |
case Success(res): policy(req, res).handle(clear); | |
}); | |
res; | |
case v: v; | |
} | |
default: actual.request(req); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment