-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsse.lua
More file actions
100 lines (89 loc) · 1.89 KB
/
sse.lua
File metadata and controls
100 lines (89 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
---@class http.SseEvent
---@field data table<string>?
---@field exit number?
---@class http.SseClient
---@field url string
---@field method string?
---@field token string?
---@field payload string?
---@field callback fun(error, event: http.SseEvent)?
---@field job number?
local SseClient = {}
SseClient.__index = SseClient
---@return http.SseClient
function SseClient.new(url)
local self = setmetatable({}, SseClient)
self.url = url
return self
end
---@return http.SseClient
function SseClient:POST()
self.method = "POST"
return self
end
---@return http.SseClient
function SseClient:body(body)
self.payload = body
return self
end
---@return http.SseClient
function SseClient:handle(handle)
self.callback = handle
return self
end
---@return http.SseClient
function SseClient:auth(token)
self.token = token
return self
end
---@param client http.SseClient
---@return table
local function _cmd(client)
local body = vim.fn.json_encode(client.payload)
local cmd = {
"curl",
"--no-buffer",
"-s",
"-X",
client.method,
"-H",
"Content-Type: application/json",
"-H",
"Authorization: Bearer " .. client.token,
"-d",
body,
client.url,
}
return cmd
end
---@param client http.SseClient
local function handle_sse_events(client)
local sid = require("kide").timer_stl_status("")
client.job = vim.fn.jobstart(_cmd(client), {
on_stdout = function(_, data, _)
client.callback(nil, {
data = data,
})
end,
on_stderr = function(_, _, _)
end,
on_exit = function(_, code, _)
require("kide").clean_stl_status(sid, code)
client.callback(nil, {
data = nil,
exit = code,
})
end,
})
end
---@return http.SseClient
function SseClient:send()
handle_sse_events(self)
return self
end
function SseClient:stop()
if self.job then
pcall(vim.fn.jobstop, self.job)
end
end
return SseClient