|
| 1 | +local response = {} |
| 2 | + |
| 3 | +local config = require("rest-nvim.config") |
| 4 | +local logger = require("rest-nvim.logger") |
| 5 | + |
| 6 | +---@class rest.Response |
| 7 | +---@field status rest.Response.status |
| 8 | +---@field body string? |
| 9 | +---@field headers table<string,string> |
| 10 | + |
| 11 | +---@class rest.Response.status |
| 12 | +---@field code number |
| 13 | +---@field version string |
| 14 | + |
| 15 | +-- TODO: format asynchronously |
| 16 | + |
| 17 | +---Try format the result body |
| 18 | +---@param content_type string? |
| 19 | +---@param body string |
| 20 | +---@return string[] |
| 21 | +function response.try_format_body(content_type, body) |
| 22 | + ---@type string |
| 23 | + local res_type |
| 24 | + if content_type then |
| 25 | + res_type = vim.split(content_type, "/")[2]:gsub(";.*", "") |
| 26 | + end |
| 27 | + if res_type == "octet-stream" then |
| 28 | + return { "Binary answer" } |
| 29 | + else |
| 30 | + local formatters = config.result.behavior.formatters |
| 31 | + local fmt = formatters[res_type] |
| 32 | + if fmt then |
| 33 | + if type(fmt) == "function" then |
| 34 | + elseif vim.fn.executable(fmt[1] or fmt) then |
| 35 | + local cmd = type(fmt) == "string" and { fmt } or fmt |
| 36 | + ---@cast cmd string[] |
| 37 | + local sc = vim.system(cmd, { stdin = body }):wait() |
| 38 | + if sc.code == 0 and sc.stdout then |
| 39 | + body = sc.stdout --[[@as string]] |
| 40 | + else |
| 41 | + logger.error("Error running formatter '" .. fmt .. "' on response body:\n" .. sc.stderr) |
| 42 | + vim.notify("Formatting response body failed. See `:Rest logs` for more info", vim.log.levels.ERROR) |
| 43 | + end |
| 44 | + end |
| 45 | + elseif res_type ~= nil then |
| 46 | + local msg = ( |
| 47 | + "Could not find a formatter for the body type " |
| 48 | + .. res_type |
| 49 | + .. " returned in the request, the results will not be formatted" |
| 50 | + ) |
| 51 | + logger.info(msg) |
| 52 | + vim.notify(msg, vim.log.levels.INFO) |
| 53 | + end |
| 54 | + return vim.split(body, "\n") |
| 55 | + end |
| 56 | +end |
| 57 | + |
| 58 | +return response |
0 commit comments