comparison mod_pubsub_post/mod_pubsub_post.lua @ 4521:f7381268a597

mod_pubsub_post: Add support for mapping incoming JSON to XML Using the new util.datamapper pubsub_post_mappings[node] = filename or schema
author Kim Alvefur <zash@zash.se>
date Mon, 22 Mar 2021 21:18:35 +0100
parents 0d3926e49b55
children 08b71d02c6dc
comparison
equal deleted inserted replaced
4520:bd320ec2c2fc 4521:f7381268a597
13 sha384 = hashes.hmac_sha384; 13 sha384 = hashes.hmac_sha384;
14 sha512 = hashes.hmac_sha512; 14 sha512 = hashes.hmac_sha512;
15 }; 15 };
16 16
17 local pubsub_service = module:depends("pubsub").service; 17 local pubsub_service = module:depends("pubsub").service;
18
19 local mappings = module:get_option("pubsub_post_mappings", nil);
20 local datamapper;
21 if type(mappings) == "table" then
22 datamapper = require "util.datamapper";
23 for node, f in pairs(mappings) do
24 if type(f) == "string" then
25 local fh = assert(module:load_resource(f));
26 mappings[node] = assert(json.parse(fh:read("*a")));
27 fh:close()
28 end
29 end
30 end
31
32 local function wrap(node, parsed, raw)
33 if mappings and mappings[node] then
34 return datamapper.unparse(mappings[node], parsed)
35 end
36 return st.stanza("json", { xmlns="urn:xmpp:json:0" }):text(raw);
37 end
18 38
19 local error_mapping = { 39 local error_mapping = {
20 ["forbidden"] = 403; 40 ["forbidden"] = 403;
21 ["item-not-found"] = 404; 41 ["item-not-found"] = 404;
22 ["internal-server-error"] = 500; 42 ["internal-server-error"] = 500;
40 return { status_code = 400; body = tostring(err); } 60 return { status_code = 400; body = tostring(err); }
41 end 61 end
42 if type(parsed) ~= "table" then 62 if type(parsed) ~= "table" then
43 return { status_code = 400; body = "object or array expected"; }; 63 return { status_code = 400; body = "object or array expected"; };
44 end 64 end
45 local wrapper = st.stanza("json", { xmlns="urn:xmpp:json:0" }):text(data); 65 local payload = wrap(node, parsed, data)
46 return publish_payload(node, actor, type(parsed.id) == "string" and parsed.id or "current", wrapper); 66 return publish_payload(node, actor, type(parsed.id) == "string" and parsed.id or "current", payload);
47 end 67 end
48 68
49 local function publish_atom(node, actor, feed) 69 local function publish_atom(node, actor, feed)
50 for entry in feed:childtags("entry") do 70 for entry in feed:childtags("entry") do
51 local item_id = entry:get_child_text("id"); 71 local item_id = entry:get_child_text("id");