Comparison

mod_rest/mod_rest.lua @ 4918: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
parent 4917:9d0ec61c70a1
child 4920:bdac7c717c91
comparison
equal deleted inserted replaced
4917:9d0ec61c70a1 4918:347e34c3c7e2
228 end 228 end
229 return form; 229 return form;
230 end 230 end
231 231
232 local function encode(type, s) 232 local function encode(type, s)
233 if type == "text/plain" then
234 return s:get_child_text("body") or "";
235 elseif type == "application/xmpp+xml" then
236 return tostring(s);
237 end
238 local mapped, err = jsonmap.st2json(s);
239 if not mapped then return mapped, err; end
233 if type == "application/json" then 240 if type == "application/json" then
234 return json.encode(jsonmap.st2json(s)); 241 return json.encode(mapped);
235 elseif type == "application/x-www-form-urlencoded" then 242 elseif type == "application/x-www-form-urlencoded" then
236 return http.formencode(flatten(jsonmap.st2json(s))); 243 return http.formencode(flatten(mapped));
237 elseif type == "application/cbor" then 244 elseif type == "application/cbor" then
238 return cbor.encode(jsonmap.st2json(s)); 245 return cbor.encode(mapped);
239 elseif type == "text/plain" then 246 end
240 return s:get_child_text("body") or ""; 247 error "unsupported encoding";
241 end
242 return tostring(s);
243 end 248 end
244 249
245 local post_errors = errors.init("mod_rest", { 250 local post_errors = errors.init("mod_rest", {
246 noauthz = { code = 401, type = "auth", condition = "not-authorized", text = "No credentials provided" }, 251 noauthz = { code = 401, type = "auth", condition = "not-authorized", text = "No credentials provided" },
247 unauthz = { code = 403, type = "auth", condition = "not-authorized", text = "Credentials not accepted" }, 252 unauthz = { code = 403, type = "auth", condition = "not-authorized", text = "Credentials not accepted" },