Last active
March 5, 2016 23:19
-
-
Save noogen/6a6bb35676f68fa62c6f to your computer and use it in GitHub Desktop.
Azure table storage use as cache
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
local ACCOUNT='youraccount' | |
local KEY='youkey' | |
local azure = require('niiknow/webslib/azure.lua') | |
-- PrimaryKey is db like in redis, if not provided set to -default | |
local pKey = request.query['db'] or '-default' | |
-- RowKey is the actual key | |
local rKey = request.query['key'] | |
-- GET cache item | |
if (request.method == 'GET') then | |
local search = string.format("(PartitionKey eq '%s' and RowKey eq '%s')", pKey, rKey) | |
local tst = azure.table.list( | |
{account = ACCOUNT, key = KEY, table = 'CacheFun'} | |
, {filter = search}) | |
-- validate that it has not expired then return | |
-- else proceed to delete | |
local item = json.parse(tst.content) | |
local result = item.value[1] -- array start at 1, weird | |
if (result ~= nil and result.exp > os.time()) then | |
return result.content | |
end | |
end | |
-- if there is a content body, save it to cache | |
if (request.body) then | |
local expire = request.query['exp'] or 120 -- expire in seconds, default expire to 2 minutes | |
local payload = { | |
content = request.body, | |
PartitionKey = pKey, | |
RowKey = rKey, | |
exp = os.time() + expire | |
} | |
azure.table.update( | |
{account = ACCOUNT, key = KEY, table = 'CacheFun'} | |
, payload) | |
else -- no body means removal | |
azure.table.delete( | |
{account = ACCOUNT, key = KEY, table = 'CacheFun'} | |
, pKey, rKey) | |
end | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment