UNPKG

mindee

Version:

Mindee Client Library for Node.js

65 lines (64 loc) 2.4 kB
import { createField } from "./fieldFactory.js"; export class InferenceFields extends Map { constructor(serverResponse, indentLevel = 0) { super(Object.entries(serverResponse).map(([key, value]) => { return [key, createField(value, 1)]; })); this._indentLevel = indentLevel; } getSimpleField(fieldName) { const field = this.get(fieldName); if (field === undefined) { throw new Error(`The field '${fieldName}' was not found.`); } if (field.constructor.name !== "SimpleField") { throw new Error(`The field '${fieldName}' is not a SimpleField.`); } return field; } getObjectField(fieldName) { const field = this.get(fieldName); if (field === undefined) { throw new Error(`The field '${fieldName}' was not found.`); } if (field.constructor.name !== "ObjectField") { throw new Error(`The field '${fieldName}' is not an ObjectField.`); } return field; } getListField(fieldName) { const field = this.get(fieldName); if (field === undefined) { throw new Error(`The field '${fieldName}' was not found.`); } if (field.constructor.name !== "ListField") { throw new Error(`The field '${fieldName}' is not a ListField.`); } return field; } toString(indent = this._indentLevel) { if (this.size === 0) { return ""; } const padding = " ".repeat(indent); const lines = []; for (const [fieldKey, fieldValue] of this.entries()) { let line = `${padding}:${fieldKey}:`; if (fieldValue.constructor.name === "ListField") { const listField = fieldValue; if (Array.isArray(listField.items) && listField.items.length > 0) { line += listField.toString(); } } else if (fieldValue.constructor.name === "ObjectField") { line += fieldValue.toString(); } else if (fieldValue.constructor.name === "SimpleField") { const val = fieldValue.toString(); line += val.length > 0 ? " " + val.toString() : ""; } lines.push(line); } return lines.join("\n").trimEnd(); } }