Last active
August 29, 2015 14:01
-
-
Save didierofrivia/e99c2f006d2a14438a5d to your computer and use it in GitHub Desktop.
This file contains 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
return function (request, next_middleware) | |
-- initialize cache store | |
local threshold = 86400 -- 1 day | |
local key = 'cache=' .. request.uri_full | |
-- flush cache | |
if request.method == "DELETE" then | |
bucket.middleware.delete(key) | |
local body, status, headers = http.simple(request.uri_full) | |
return { body = body, status = status, headers = headers } | |
end | |
if request.method == "GET" then | |
-- request new one | |
if request.args.new and request.args.hits < "3" then | |
console.log("new one!") | |
key = 'new=http://' .. request.host .. request.uri | |
console.log(key) | |
local response = next_middleware() | |
bucket.middleware.set(key, response) | |
send.event({channel = "cache", msg = "new content demanded", level = "debug", content = response }) | |
return response | |
end | |
local stored = bucket.middleware.get(key) | |
if stored ~= nil then | |
console.log("stored") | |
console.log(stored) | |
local expires = stored.headers['X-Expires'] | |
if expires and expires > time.now() then -- not expired yet | |
--send.event({channel = "cache", msg = "returned cached content", level = "debug", key = key, content = stored, expires = expires, now = time.now() }) | |
stored.headers['Expires'] = time.http(expires) | |
end | |
console.log(key) | |
return stored | |
end | |
--send.event({channel = "cache", msg = "NOT cached content", level = "debug", key = key, content = stored, expires = expires, now = time.now() }) | |
end | |
-- if content is not cached, do the real request & get response | |
local response = next_middleware() | |
if request.method == 'GET' then | |
local expires = time.now() + threshold | |
response.headers['X-Expires'] = expires | |
bucket.middleware.set(key, response, expires) | |
send.event({channel = "cache", msg = "stored cached content", level = "debug", content = response }) | |
end | |
return response | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment