Repository navigation
Expand file tree
/
Copy patharray.js
More file actions
57 lines (51 loc) · 1.95 KB
/
Copy patharray.js
File metadata and controls
57 lines (51 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { traverse } from '../traverse';
import { applyXMLAttributes, getXMLAttributes, prefixed } from '../utils';
export function sampleArray(schema, options = {}, spec, context) {
const depth = (context && context.depth || 1);
let arrayLength = Math.min(schema.maxItems != undefined ? schema.maxItems : Infinity, schema.minItems || 1);
// for the sake of simplicity, we're treating `contains` in a similar way to `items`
const items = schema.prefixItems || schema.items || schema.contains;
if (Array.isArray(items)) {
arrayLength = Math.max(arrayLength, items.length);
}
let itemSchemaGetter = itemNumber => {
if (Array.isArray(items)) {
return items[itemNumber] || {};
}
return items || {};
};
let res = [];
if (!items) return res;
for (let i = 0; i < arrayLength; i++) {
let itemSchema = itemSchemaGetter(i);
let { value: sample } = traverse(itemSchema, options, spec, { depth: depth + 1 });
if (options?.format === 'xml') {
let { value, propertyName } = applyXMLAttributes({ value: sample }, itemSchema, context, spec);
if (!propertyName && (value === null || typeof value !== 'object')) {
const { name, prefix } = getXMLAttributes(schema);
propertyName = prefixed(name || 'root', prefix);
}
if (propertyName) {
if (!res?.[propertyName]) {
res = { ...res, [propertyName]: [] };
}
res[propertyName].push(value);
} else {
res = { ...res, ...value };
}
} else {
res.push(sample);
}
}
if (options?.format === 'xml' && depth === 1) {
const { value, propertyName } = applyXMLAttributes({ value: null }, schema, context, spec);
if (propertyName) {
if (value) {
res = Array.isArray(res) ? { [propertyName]: { ...value, ...res.map(item => ({ ['#text']: { ...item } })) } } : { [propertyName]: { ...res, ...value } };
} else {
res = { [propertyName]: res };
}
}
}
return res;
}