1 |
|
2 |
|
3 |
|
4 | !function(exports) {
|
5 | exports.schemaApply = schemaApply
|
6 |
|
7 | function allOf(schema) {
|
8 | return Array.isArray(schema.allOf) ?
|
9 | schema.allOf.reduce(function(memo, item) {
|
10 | return JSON.mergePatch(memo, item)
|
11 | }, {}):
|
12 | schema
|
13 | }
|
14 |
|
15 | function schemaApply(schema, data, _required) {
|
16 | var tmp
|
17 | , type = schema.type
|
18 | , actualType = typeof data
|
19 | , required = _required || schema.required
|
20 |
|
21 | schema = allOf(schema)
|
22 |
|
23 | if (schema.anyOf) {
|
24 | schema.anyOf.map(allOf).each(function(schema) {
|
25 | var i, tmp, tmp2
|
26 | , keys = Object.keys(schema.properties)
|
27 |
|
28 | for (i = 0; tmp = keys[i++]; ) {
|
29 | tmp2 = schema.properties[tmp]["enum"]
|
30 | if (tmp2 && tmp2.indexOf(data[tmp]) == -1) {
|
31 | return
|
32 | }
|
33 | }
|
34 | schemaApply(schema, data)
|
35 | })
|
36 | }
|
37 | if (Array.isArray(tmp = schema["enum"])) {
|
38 | if (tmp.indexOf(data) === -1) {
|
39 | for (var i = tmp.length; i--; ) {
|
40 | if (tmp[i] == data) {
|
41 | data = tmp[i]
|
42 | break
|
43 | }
|
44 | }
|
45 | }
|
46 | } else if (type == "string") {
|
47 | if (type !== actualType) data = "" + data
|
48 | } else if (type === "number" || type == "integer") {
|
49 | data = (data + "").replace(",", ".")
|
50 | data = type === "number" ? parseFloat(data) : parseInt(data, 10)
|
51 |
|
52 | if (typeof(tmp = schema.multipleOf) == "number") {
|
53 | data -= data % tmp
|
54 | }
|
55 | if (typeof(tmp = schema.minimum) == "number" && data < tmp) {
|
56 | data = tmp
|
57 | }
|
58 | if (typeof(tmp = schema.maximum) == "number" && data > tmp) {
|
59 | data = tmp
|
60 | }
|
61 | } else if (type == "boolean" ) {
|
62 | data = data ? true : required ? false : null
|
63 | } else if (type == "date-time") {
|
64 | data = data.date()
|
65 | } else if (schema.type == "array" ) {
|
66 | var itemSchema = Array.isArray(schema.items) && schema.items
|
67 |
|
68 | data = Array.isArray(data) ?
|
69 | data.reduce(function(memo, item, idx) {
|
70 | var sc = itemSchema ? itemSchema[idx] : schema.items
|
71 | if (item !== void null && sc) {
|
72 | item = schemaApply(sc, item)
|
73 | memo.push(item)
|
74 | }
|
75 | return memo
|
76 | }, []) :
|
77 | null
|
78 | } else {
|
79 | var reqArr = Array.isArray(schema.required) && schema.required
|
80 | Object.each(schema.properties, function(propSchema, prop) {
|
81 | if (data[prop] !== void 0) {
|
82 | data[prop] = schemaApply(
|
83 | propSchema,
|
84 | data[prop],
|
85 | reqArr && reqArr.indexOf(prop) > -1
|
86 | )
|
87 | }
|
88 | })
|
89 | }
|
90 |
|
91 | return data
|
92 | }
|
93 | }(this.JSON || this)
|
94 |
|