Module:PriceServer: Difference between revisions

From The Blockheads Wiki
(Created page with "local Prices = {} local function fetchPrices() local apiUrl = "http://priceserver.theblockheads.net/get_prices.php" local response, code = mw.http.get(apiUrl) if code ~= 200 then return nil, "Error retrieving prices " .. tostring(code) end -- Parse the response local json = require('json') return json.decode(response) end function Prices.getPrice(id) local pricesData, err = fetchPrices() if err then return err end if pricesData th...")
 
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
local Prices = {}
local PriceServer = {}


local function fetchPrices()
local function fetchPrices()
local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
local response, code = mw.http.get(apiUrl)
local response, code = http.get(apiUrl)
if code ~= 200 then
if code ~= 200 then
Line 14: Line 14:
end
end


function Prices.getPrice(id)
function PriceServer.getPrice(id)
     local pricesData, err = fetchPrices()
     local pricesData, err = fetchPrices()


Line 32: Line 32:
end
end


return Prices
function PriceServer.getPriceGraphImage(id)
        return string.format('<img src="http://priceserver.theblockheads.net/get_price_graph_data.php?item_id=%s" alt="Price graph for item %s" />', tostring(id), tostring(id))
end
 
return PriceServer

Latest revision as of 13:03, 29 October 2024

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

local PriceServer = {}

local function fetchPrices()
	local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
	local response, code = http.get(apiUrl)
	
	if code ~= 200 then
		return nil, "Error retrieving prices " .. tostring(code)
	end
	
	-- Parse the response
	local json = require('json')
	return json.decode(response)
end

function PriceServer.getPrice(id)
    local pricesData, err = fetchPrices()

    if err then
        return err
    end

    if pricesData then
        for _, item in ipairs(pricesData) do
            if item.id == id then
                return string.format("%.2f", tonumber(item.price)) -- Round to two decimal places
            end
        end
    end

    return "Item not found."
end

function PriceServer.getPriceGraphImage(id)
        return string.format('<img src="http://priceserver.theblockheads.net/get_price_graph_data.php?item_id=%s" alt="Price graph for item %s" />', tostring(id), tostring(id))
end

return PriceServer