Get rid of curl

This commit is contained in:
Jonas Widen 2025-03-16 19:04:32 +01:00
parent a6a8c28462
commit c532849cbf

View File

@ -8,85 +8,43 @@ function Request.new(url, payload)
local self = setmetatable({}, Request)
self.url = url
self.payload = payload
self.response = ""
self.error_msg = ""
self.stdout = vim.loop.new_pipe()
self.stderr = vim.loop.new_pipe()
self.handle = nil
return self
end
function Request:cleanup()
if self.stdout then self.stdout:close() end
if self.stderr then self.stderr:close() end
if self.handle then self.handle:close() end
end
function Request:handle_error(callback, msg)
self:cleanup()
vim.schedule(function()
callback(nil, msg)
end)
end
function Request:setup_pipes(callback)
self.stdout:read_start(function(err, chunk)
if err then
self:handle_error(callback, "Read error: " .. err)
return
end
if chunk then
self.response = self.response .. chunk
end
end)
self.stderr:read_start(function(err, chunk)
if err then
self:handle_error(callback, "Error reading stderr: " .. err)
return
end
if chunk then
self.error_msg = self.error_msg .. chunk
end
end)
end
function Request:execute(callback)
self.handle = vim.loop.spawn('curl', {
args = {
'-s',
'-X', 'POST',
'-H', 'Content-Type: application/json',
'-d', self.payload,
self.url
},
stdio = {nil, self.stdout, self.stderr}
}, function(exit_code)
self:cleanup()
local headers = {
['Content-Type'] = 'application/json',
}
if exit_code ~= 0 then
vim.loop.http_request({
url = self.url,
method = 'POST',
headers = headers,
body = self.payload
}, function(err, response)
if err then
vim.schedule(function()
callback(nil, "Curl failed with code " .. exit_code .. ": " .. self.error_msg)
callback(nil, "HTTP request failed: " .. err)
end)
return
end
local success, decoded = pcall(vim.json.decode, self.response)
if response.status ~= 200 then
vim.schedule(function()
callback(nil, "HTTP request failed with status " .. response.status)
end)
return
end
local success, decoded = pcall(vim.json.decode, response.body)
vim.schedule(function()
if success then
callback(decoded)
else
callback(nil, "JSON decode error: " .. self.response)
callback(nil, "JSON decode error: " .. response.body)
end
end)
end)
if not self.handle then
self:handle_error(callback, "Failed to start curl")
return
end
self:setup_pipes(callback)
end
M.Request = Request