@@ -3,6 +3,17 @@ local curl = require("plenary.curl")
33local config = require (" rest-nvim.config" )
44
55local M = {}
6+ -- checks if 'x' can be executed by system()
7+ local function is_executable (x )
8+ if type (x ) == " string" and vim .fn .executable (x ) == 1 then
9+ return true
10+ elseif vim .tbl_islist (x ) and vim .fn .executable (x [1 ] or " " ) == 1 then
11+ return true
12+ end
13+
14+ return false
15+ end
16+
617-- get_or_create_buf checks if there is already a buffer with the rest run results
718-- and if the buffer does not exists, then create a new one
819M .get_or_create_buf = function ()
@@ -89,8 +100,26 @@ local function create_callback(method, url)
89100 --- Add the curl command results into the created buffer
90101 local formatter = config .get (" result" ).formatters [content_type ]
91102 -- formate response body
92- if formatter and vim .fn .executable (type (formatter ) == " string" and formatter or formatter [1 ]) == 1 then
93- res .body = vim .fn .system (formatter , res .body ):gsub (" \n $" , " " )
103+ if type (formatter ) == " function" then
104+ local ok , out = pcall (formatter , res .body )
105+ -- check if formatter ran successfully
106+ if ok and out then
107+ res .body = out
108+ else
109+ vim .api .nvim_echo ({{
110+ string.format (" Error calling formatter on response body:\n %s" , out ), " Error"
111+ }}, false , {})
112+ end
113+ elseif is_executable (formatter ) then
114+ local stdout = vim .fn .system (formatter , res .body ):gsub (" \n $" , " " )
115+ -- check if formatter ran successfully
116+ if vim .v .shell_error == 0 then
117+ res .body = stdout
118+ else
119+ vim .api .nvim_echo ({{
120+ string.format (" Error running formatter %s on response body:\n %s" , vim .inspect (formatter ), stdout ), " Error"
121+ }}, false , {})
122+ end
94123 end
95124
96125 -- append response container
0 commit comments