mod_rest/mod_rest.lua
changeset 4041 991090cb5d18
parent 4040 04c11b652aeb
child 4070 07ae583bc565
equal deleted inserted replaced
4040:04c11b652aeb 4041:991090cb5d18
    12 local jid = require "util.jid";
    12 local jid = require "util.jid";
    13 local json = require "util.json";
    13 local json = require "util.json";
    14 local st = require "util.stanza";
    14 local st = require "util.stanza";
    15 local um = require "core.usermanager";
    15 local um = require "core.usermanager";
    16 local xml = require "util.xml";
    16 local xml = require "util.xml";
       
    17 local have_cbor, cbor = pcall(require, "cbor");
    17 
    18 
    18 local jsonmap = module:require"jsonmap";
    19 local jsonmap = module:require"jsonmap";
    19 
    20 
    20 local tokens = module:depends("tokenauth");
    21 local tokens = module:depends("tokenauth");
    21 
    22 
    66 		local parsed, err = json.decode(data);
    67 		local parsed, err = json.decode(data);
    67 		if not parsed then
    68 		if not parsed then
    68 			return parsed, err;
    69 			return parsed, err;
    69 		end
    70 		end
    70 		return jsonmap.json2st(parsed);
    71 		return jsonmap.json2st(parsed);
       
    72 	elseif mimetype == "application/cbor" and have_cbor then
       
    73 		local parsed, err = cbor.decode(data);
       
    74 		if not parsed then
       
    75 			return parsed, err;
       
    76 		end
       
    77 		return jsonmap.json2st(parsed);
    71 	elseif mimetype == "application/x-www-form-urlencoded"then
    78 	elseif mimetype == "application/x-www-form-urlencoded"then
    72 		local parsed = http.formdecode(data);
    79 		local parsed = http.formdecode(data);
    73 		if type(parsed) == "string" then
    80 		if type(parsed) == "string" then
    74 			return parse("text/plain", parsed);
    81 			return parse("text/plain", parsed);
    75 		end
    82 		end
   104 local supported_outputs = {
   111 local supported_outputs = {
   105 	"application/xmpp+xml",
   112 	"application/xmpp+xml",
   106 	"application/json",
   113 	"application/json",
   107 };
   114 };
   108 
   115 
       
   116 if have_cbor then
       
   117 	table.insert(supported_inputs, "application/cbor");
       
   118 	table.insert(supported_outputs, "application/cbor");
       
   119 end
       
   120 
   109 local function encode(type, s)
   121 local function encode(type, s)
   110 	if type == "application/json" then
   122 	if type == "application/json" then
   111 		return json.encode(jsonmap.st2json(s));
   123 		return json.encode(jsonmap.st2json(s));
       
   124 	elseif type == "application/cbor" then
       
   125 		return cbor.encode(jsonmap.st2json(s));
   112 	elseif type == "text/plain" then
   126 	elseif type == "text/plain" then
   113 		return s:get_child_text("body") or "";
   127 		return s:get_child_text("body") or "";
   114 	end
   128 	end
   115 	return tostring(s);
   129 	return tostring(s);
   116 end
   130 end