http refactor

This commit is contained in:
Linventif 2023-11-18 00:00:33 +01:00
parent 7bc6851780
commit cee4f3297f

View File

@ -2,15 +2,41 @@
// HTTP
//
local failMessage = {
["401"] = "Bad Credentials",
["403"] = "Forbidden",
["404"] = "Not Found",
["500"] = "Internal Server Error",
["503"] = "Service Unavailable",
["504"] = "Gateway Timeout",
}
local function errorMessage(body, code)
if (body && body.error) then
if (failMessage[code]) then
return failMessage[code]
else
return body.error
end
elseif (failMessage[code]) then
return failMessage[code]
else
return code
end
end
local function sendHTTP(params)
// Log the HTTP request
gmInte.log("HTTP Request: " .. params.method .. " " .. params.endpoint, true)
gmInte.log("HTTP Body: " .. (params.body || "No body"), true)
// Send the HTTP request
HTTP({
url = "https://api.gmod-integration.com" .. params.endpoint,
method = params.method,
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = params.body and string.len(params.body) || 0,
["Content-Length"] = params.body && string.len(params.body) || 0,
["id"] = gmInte.config.id,
["token"] = gmInte.config.token,
["version"] = gmInte.version
@ -18,17 +44,27 @@ local function sendHTTP(params)
body = params.body && params.body || "",
type = "application/json",
success = function(code, body, headers)
// Log the HTTP response
gmInte.log("HTTP Response: " .. code, true)
if (gmInte.debug) then gmInte.log("HTTP Body: " .. body, true) end
// if body and is json extract it
if (body && string.sub(headers["Content-Type"], 1, 16) == "application/json") then
body = util.JSONToTable(body)
end
// Check if the request was successful
if (string.sub(code, 1, 1) == "2") then
if (params.success) then
params.success(code, body, headers)
else
gmInte.log("HTTP Request Successful", true)
end
else
if (params.failed) then
params.failed(code, body, headers)
else
gmInte.logError("HTTP Request failed with code " .. code)
gmInte.logError(errorMessage(body, code))
end
end
end,
@ -74,32 +110,4 @@ function gmInte.delete(endpoint, onSuccess, onFailed)
success = onSuccess,
failed = onFailed
})
end
/*
// Fetch Example
gmInte.fetch(
// Endpoint
"",
// Parameters
{ request = "requ" },
// onSuccess
function( body, length, headers, code )
print(body)
end
)
// Post Example
gmInte.post(
// Endpoint
"",
// Data
{
data = "data"
},
// onSuccess
function( body, length, headers, code )
print(body)
end
)
*/
end