changeset 4919:347e34c3c7e2

mod_rest: Improve error handling during format mapping Prevents e.g. a nil, error return going directly into e.g. json encoding, resulting in "null" being returned. Further handling improvements down the line is needed.
author Kim Alvefur <zash@zash.se>
date Thu, 07 Apr 2022 17:49:08 +0200
parents 9d0ec61c70a1
children b9f8dd9a7fdb
files mod_rest/mod_rest.lua
diffstat 1 files changed, 11 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/mod_rest/mod_rest.lua	Thu Apr 07 17:48:08 2022 +0200
+++ b/mod_rest/mod_rest.lua	Thu Apr 07 17:49:08 2022 +0200
@@ -230,16 +230,21 @@
 end
 
 local function encode(type, s)
+	if type == "text/plain" then
+		return s:get_child_text("body") or "";
+	elseif type == "application/xmpp+xml" then
+		return tostring(s);
+	end
+	local mapped, err = jsonmap.st2json(s);
+	if not mapped then return mapped, err; end
 	if type == "application/json" then
-		return json.encode(jsonmap.st2json(s));
+		return json.encode(mapped);
 	elseif type == "application/x-www-form-urlencoded" then
-		return http.formencode(flatten(jsonmap.st2json(s)));
+		return http.formencode(flatten(mapped));
 	elseif type == "application/cbor" then
-		return cbor.encode(jsonmap.st2json(s));
-	elseif type == "text/plain" then
-		return s:get_child_text("body") or "";
+		return cbor.encode(mapped);
 	end
-	return tostring(s);
+	error "unsupported encoding";
 end
 
 local post_errors = errors.init("mod_rest", {