UNPKG

@har-sdk/openapi-sampler

Version:

[![Maintainability](https://api.codeclimate.com/v1/badges/4acaec95c82465cb2c3d/maintainability)](https://codeclimate.com/github/NeuraLegion/har-sdk/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/4acaec95c82465cb2c3d/test_coverage

63 lines 2.63 kB
import { VendorExtensions } from './VendorExtensions'; export class VendorExampleExtractor { extract(schema) { return [ schema[VendorExtensions.X_EXAMPLE], schema[VendorExtensions.X_EXAMPLES] ].reduce((acc, example) => (acc ? acc : this.findExampleByShape(example, schema)), undefined); } findExampleByShape(example, schema) { const exampleShape = this.getExampleShape(schema); const isPrimitiveType = 0 === exampleShape.objectKeys.length && exampleShape.arrayDepth === 0; if (isPrimitiveType) { return example; } return this.traverse(example, exampleShape); } getExampleShape(schema, depth = 0) { if ('items' in schema) { return this.getExampleShape(schema.items, 1 + depth); } return { arrayDepth: depth, objectKeys: 'properties' in schema && schema.properties ? Object.keys(schema.properties) : [] }; } traverse(example, exampleShape, possibleExample = []) { if (!example || typeof example !== 'object') { return undefined; } if (exampleShape.arrayDepth > 0 && Array.isArray(example)) { return this.traverseArray(example, exampleShape, possibleExample); } return Array.isArray(example) ? undefined : this.traverseObject(example, exampleShape, possibleExample); } traverseArray(example, exampleShape, possibleExample) { if (exampleShape.arrayDepth > 0 && Array.isArray(example)) { possibleExample.push(example); return this.traverseArray([...example, undefined].shift(), { ...exampleShape, arrayDepth: exampleShape.arrayDepth - 1 }, possibleExample); } return !!example && (Array.isArray(example) || exampleShape.arrayDepth > 0) ? undefined : this.traverseObject(example, exampleShape, possibleExample); } traverseObject(example, exampleShape, possibleExample) { const objectKeys = Object.keys(example !== null && example !== void 0 ? example : {}); if (exampleShape.arrayDepth === 0 && objectKeys.every((key) => exampleShape.objectKeys.includes(key))) { return possibleExample.length > 0 ? possibleExample.shift() : example; } return objectKeys .map((key) => this.traverse(example[key], exampleShape)) .filter((obj) => !!obj) .shift(); } } //# sourceMappingURL=VendorExampleExtractor.js.map