Comparison

util/datamapper.lua @ 11435:a1fa6202fa13

util.datamapper: Library for extracting data from stanzas Based on the XML support in the OpenAPI specification.
author Kim Alvefur <zash@zash.se>
date Sun, 07 Mar 2021 00:57:36 +0100
child 11436:5df9ffc25bb4
comparison
equal deleted inserted replaced
11434:66d4067bdfb2 11435:a1fa6202fa13
1 local st = require("util.stanza");
2
3 local function toboolean(s)
4 if s == "true" or s == "1" then
5 return true
6 elseif s == "false" or s == "0" then
7 return false
8 end
9 end
10
11 local function parse_object(schema, s)
12 local out = {}
13 if schema.properties then
14 for prop, propschema in pairs(schema.properties) do
15
16 local name = prop
17 local namespace = s.attr.xmlns;
18 local prefix = nil
19 local is_attribute = false
20 local is_text = false
21
22 local proptype
23 if type(propschema) == "table" then
24 proptype = propschema.type
25 elseif type(propschema) == "string" then
26 proptype = propschema
27 end
28
29 if type(propschema) == "table" and propschema.xml then
30 if propschema.xml.name then
31 name = propschema.xml.name
32 end
33 if propschema.xml.namespace then
34 namespace = propschema.xml.namespace
35 end
36 if propschema.xml.prefix then
37 prefix = propschema.xml.prefix
38 end
39 if propschema.xml.attribute then
40 is_attribute = true
41 elseif propschema.xml.text then
42 is_text = true
43 end
44 end
45
46 if is_attribute then
47 local attr = name
48 if prefix then
49 attr = prefix .. ":" .. name
50 elseif namespace ~= s.attr.xmlns then
51 attr = namespace .. "\1" .. name
52 end
53 if proptype == "string" then
54 out[prop] = s.attr[attr]
55 elseif proptype == "integer" or proptype == "number" then
56
57 out[prop] = tonumber(s.attr[attr])
58 elseif proptype == "boolean" then
59 out[prop] = toboolean(s.attr[attr])
60
61 end
62
63 elseif is_text then
64 if proptype == "string" then
65 out[prop] = s:get_text()
66 elseif proptype == "integer" or proptype == "number" then
67 out[prop] = tonumber(s:get_text())
68 end
69
70 else
71
72 if proptype == "string" then
73 out[prop] = s:get_child_text(name, namespace)
74 elseif proptype == "integer" or proptype == "number" then
75 out[prop] = tonumber(s:get_child_text(name, namespace))
76 elseif proptype == "object" and type(propschema) == "table" then
77 local c = s:get_child(name, namespace)
78 if c then
79 out[prop] = parse_object(propschema, c);
80 end
81
82 end
83 end
84 end
85 end
86
87 return out
88 end
89
90 local function parse(schema, s)
91 if schema.type == "object" then
92 return parse_object(schema, s)
93 end
94 end
95
96 return {parse = parse}