Module:RecursiveSelectiveList

Revision as of 06:54, 22 December 2024 by EnWikiAdmin (talk | contribs)

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

local p = {}

-- Function to fetch category members
function p.getCategoryMembers(categoryName, limit)
    -- Validate input
    if not categoryName or categoryName == "" then
        return "Error: Please provide a valid category name."
    end

    -- Set default limit if not provided
    limit = limit or 10

    -- Prepare API request parameters
    local params = {
        action = "query",
        list = "categorymembers",
        cmtitle = "Category:" .. categoryName,
        cmlimit = tostring(limit),
        format = "json"
    }

    -- Make the API request
    local apiUrl = mw.uri.fullUrl('api.php', params)
    local response = mw.http.get(apiUrl)

    -- Check for HTTP request errors
    if response.status ~= 200 then
        return "Error: HTTP request failed with status code " .. response.status
    end

    -- Parse the JSON response
    local data = mw.text.jsonDecode(response.body)
    if not data then
        return "Error: Failed to parse JSON response."
    end

    -- Check for query errors
    if not data.query or not data.query.categorymembers then
        return "Error: No category members found or invalid category."
    end

    -- Generate a bulleted list of category members
    local output = {}
    for _, member in ipairs(data.query.categorymembers) do
        table.insert(output, "* [[" .. member.title .. "]]")
    end

    -- Return the concatenated list
    return table.concat(output, "\n")
end

-- Main function for `#invoke`
function p.main(frame)
    local args = frame:getParent().args
    local categoryName = args['categoryName']
    local limit = tonumber(args['limit'])

    if not categoryName then
        return "Error: Please provide a category name."
    end

    -- Call the function to fetch category members
    return p.getCategoryMembers(categoryName, limit)
end

return p