UNPKG

diffusion

Version:

Diffusion JavaScript client

98 lines (97 loc) 3.71 kB
"use strict"; /** * @module diffusion.datatypes.RecordV2 */ Object.defineProperty(exports, "__esModule", { value: true }); exports.SchemaParser = void 0; var errors_1 = require("./../../../../errors/errors"); var schema_builder_impl_1 = require("./../../../data/record/schema/schema-builder-impl"); /** * A parser that can parse a JSON string and create a {@link SchemaImpl} */ var SchemaParser = /** @class */ (function () { /** * Create a SchemaParser * * @param recordV2Constructor a constructor function for creating * {@link RecordV2} implementations */ function SchemaParser(recordV2Constructor) { this.recordV2Constructor = recordV2Constructor; } /** * Parse a JSON string * * @param jsonString the JSON string * @return a schema object * * @throws a {@link SchemaParseError} if the JSON string could not be converted into a schema * @throws a {@link SchemaViolationError} if the JSON string does not represent a valid schema */ SchemaParser.prototype.parse = function (jsonString) { var builder = new schema_builder_impl_1.SchemaBuilderImpl(this.recordV2Constructor); var json; try { json = JSON.parse(jsonString); } catch (e) { throw new errors_1.SchemaParseError('Invalid Schema JSON string'); } if (json.records === undefined) { throw new errors_1.SchemaParseError('Schema has no records'); } try { json.records.forEach(function (record) { if (record.occurs !== undefined) { builder.record(record.name, record.occurs); } else { builder.record(record.name, record.min, record.max); } if (record.fields) { record.fields.forEach(function (field) { var min; var max; if (field.occurs !== undefined) { min = field.occurs; max = field.occurs; } else { min = field.min; max = field.max; } var type = field.type || 'STRING'; switch (type.toUpperCase()) { case 'STRING': builder.string(field.name, min, max); break; case 'INTEGER': builder.integer(field.name, min, max); break; case 'DECIMAL': var scale = field.scale || 2; builder.decimal(field.name, scale, min, max); break; default: throw new errors_1.SchemaParseError("Invalid field type value '" + type + "'"); } }); } }); return builder.build(); } catch (e) { if (e instanceof errors_1.SchemaParseError) { throw e; } else if (e instanceof Error) { throw new errors_1.SchemaParseError(e.message); } else { throw new errors_1.SchemaParseError('Could not parse schema JSON string'); } } }; return SchemaParser; }()); exports.SchemaParser = SchemaParser;