Module:DatasetLoader: Difference between revisions

// via Wikitext Extension for VSCode
// via Wikitext Extension for VSCode
 
(6 intermediate revisions by the same user not shown)
Line 1: Line 1:
-- Module:DatasetLoader
--[[
-- Central loader for Data: JSON assets via JsonConfig or mw.loadData, cached per render
* Name: DatasetLoader
* Author: Mark W. Datysgeld
* Description: Central loader for Data: JSON assets via JsonConfig or mw.loadData, cached per render
* Notes: Tries JsonConfig extension first, then falls back to mw.loadData from Data: namespace; caches results to improve performance
]]


local loader = {}
local DatasetLoader = {}
local cache = {}


-- Returns a Lua table for the named dataset, or {} on failure
-- Retrieve a dataset by name (without extension). Returns a Lua table or {}.
function loader.get(name)
function DatasetLoader.get(name)
     -- Try JsonConfig extension first
     -- Return cached if available
     if mw.ext and mw.ext.data and mw.ext.data.get then
    if cache[name] then
        local ok, data = pcall(mw.ext.data.get, name)
        return cache[name]
         if ok and data then
    end
             return data
 
    -- Ensure filename has .json extension
    local fullName = name
     if not fullName:match('%.%w+$') then
        fullName = fullName .. '.json'
    end
 
    local data
 
    -- Try JsonConfig extension (mw.ext.data.get)
    local success, result = pcall(function()
        return mw.ext.data.get(fullName)
    end)
    if success and type(result) == 'table' then
        data = result
    else
        -- Fallback to mw.loadData from Data: namespace
        success, result = pcall(function()
            return mw.loadData('Data:' .. fullName)
        end)
         if success and type(result) == 'table' then
             data = result
         end
         end
     end
     end


     -- Fallback to mw.loadData for Data: namespace
     -- Default to empty table on any failure
     local ok2, data2 = pcall(mw.loadData, 'Data:' .. name .. '.json')
     if not data or type(data) ~= 'table' then
    if ok2 and data2 then
         data = {}
         return data2
     end
     end


     -- Ultimate fallback: empty table
     -- Cache and return
     return {}
    cache[name] = data
     return data
end
end


return loader
return DatasetLoader