Module:Cache

local p = {} local libraryUtil = require('libraryUtil')

local i18n = { log = { not_cached = 'No cached version found. Storing.' }, variable_name = 'cargo_cache', }

local function make_key(key_args, prefix) local key_parts = {prefix} for _,v in pairs(key_args) do   if type(v) == 'string' then table.insert(key_parts, v)   end end return table.concat(key_parts, '_') end

local function read_cache local raw_cache = mw.getCurrentFrame:callParserFunction{ name='#var', args=i18n.variable_name }

if raw_cache ~= '' then return mw.text.jsonDecode(raw_cache) else return {} end end

local function write_cache(key, value) local cache = read_cache(key) cache[key] = value

local raw_cache = mw.getCurrentFrame:callParserFunction{ name='#vardefineecho', args={i18n.variable_name, mw.text.jsonEncode(cache)} } return cache end

function p.auto(func, args, prefix) libraryUtil.checkType('auto', 1, func, 'function') libraryUtil.checkType('auto', 2, args, 'table') libraryUtil.checkType('auto', 3, prefix, 'string', true)

local key = make_key(args, prefix)

if read_cache[key] then return read_cache[key] else mw.log(i18n.log.not_cached) return write_cache(key, func(args))[key] end end

function p.set(args, value, prefix) libraryUtil.checkType('set', 1, args, 'table') libraryUtil.checkTypeMulti('set', 2, value, { 'string', 'table' }) libraryUtil.checkType('set', 3, prefix, 'string', true) local key = make_key(args, prefix) return write_cache(key, value)[key] end

function p.get(args, prefix) libraryUtil.checkType('get', 2, args, 'table') libraryUtil.checkType('get', 3, prefix, 'string', true) local key = make_key(args, prefix) return read_cache[key] end

return p