Module:RecursiveSelectiveList

Revision as of 07:35, 22 December 2024 by EnWikiAdmin (talk | contribs)

Documentation for this module may be created at Module:RecursiveSelectiveList/doc

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

function p.main(frame)
    -- Get the category name from the template arguments
    local args = frame.args
    local categoryName = args.categoryName

    -- Validate the category name
    if not categoryName or categoryName == "" then
        return "Error: 'categoryName' parameter is missing or empty."
    end

    -- Ensure the category name starts with "Category:"
    if not categoryName:match("^Category:") then
        categoryName = "Category:" .. categoryName
    end

    -- Fetch category members using the API
    local members = p.getCategoryMembers(categoryName)

    -- Handle empty categories
    if not members or #members == 0 then
        return "The category '" .. categoryName .. "' has no members."
    end

    -- Return the list of members as a comma-separated string
    return table.concat(members, ", ")
end

function p.getCategoryMembers(categoryName)
    local members = {}

    -- Use MediaWiki API to query category members
    local success, result = p.callAPI{
        action = "query",
        list = "categorymembers",
        cmtitle = categoryName,
        cmlimit = "max", -- Get up to 500 members (or server limit)
        format = "json"
    }

    if not success then
        return members -- Return an empty table on failure
    end

    -- Extract member titles from the API result
    for _, member in ipairs(result.query.categorymembers) do
        table.insert(members, member.title)
    end

    return members
end

function p.callAPI(params)
    -- Make an API call
    local success, result = pcall(function()
        return mw.ext.data.getJson(mw.site.api(params))
    end)

    if success then
        return true, result
    else
        return false, nil
    end
end

return p