65 lines
1.7 KiB
Lua
65 lines
1.7 KiB
Lua
local Job = require('plenary.job')
|
|
local api = {}
|
|
|
|
-- Helper function for making async requests to Gitea API via curl
|
|
local function request(method, base_url, endpoint, token, data, callback)
|
|
local headers = {
|
|
"Content-Type: application/json",
|
|
"Authorization: token " .. token
|
|
}
|
|
|
|
local curl_args = {
|
|
"-s", -- silent mode
|
|
"-X", method, -- GET, POST, PATCH, etc.
|
|
base_url .. endpoint,
|
|
"-H", headers[1],
|
|
"-H", headers[2]
|
|
}
|
|
|
|
if data then
|
|
local json_data = vim.fn.json_encode(data)
|
|
table.insert(curl_args, "-d")
|
|
table.insert(curl_args, json_data)
|
|
end
|
|
|
|
Job:new({
|
|
command = "curl",
|
|
args = curl_args,
|
|
on_exit = function(j, return_val)
|
|
if return_val == 0 then
|
|
local result = table.concat(j:result(), "\n")
|
|
local ok, decoded = pcall(vim.fn.json_decode, result)
|
|
if ok then
|
|
callback(decoded, nil)
|
|
else
|
|
callback(nil, "Failed to decode JSON. Response: " .. result)
|
|
end
|
|
else
|
|
callback(nil, "Curl request failed with return code: " .. return_val)
|
|
end
|
|
end
|
|
}):start()
|
|
end
|
|
|
|
function api.get(base_url, endpoint, token, cb)
|
|
request("GET", base_url, endpoint, token, nil, cb)
|
|
end
|
|
|
|
function api.post(base_url, endpoint, token, data, cb)
|
|
request("POST", base_url, endpoint, token, data, cb)
|
|
end
|
|
|
|
function api.patch(base_url, endpoint, token, data, cb)
|
|
request("PATCH", base_url, endpoint, token, data, cb)
|
|
end
|
|
|
|
function api.put(base_url, endpoint, token, data, cb)
|
|
request("PUT", base_url, endpoint, token, data, cb)
|
|
end
|
|
|
|
function api.delete(base_url, endpoint, token, cb)
|
|
request("DELETE", base_url, endpoint, token, nil, cb)
|
|
end
|
|
|
|
return api
|