import type { PropertyParser } from '../../types'; import { InvalidStringRecord } from './exception'; /** Парсит JSON в плоский объект, проверяя, что все значения — строки. */ export class StringRecordParser implements PropertyParser> { type(): string { return 'json(Record)'; } description(): string { return 'Parses a JSON object whose values are all strings'; } parse(value: unknown): Record { const parsed = this.toJson(value); if ( parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) ) { throw new InvalidStringRecord('expected a JSON object', value); } const result: Record = {}; for (const [key, item] of Object.entries(parsed)) { if (typeof item !== 'string') { throw new InvalidStringRecord( `value of key <${key}> must be a string, got ${typeof item}`, value, ); } result[key] = item; } return result; } private toJson(value: unknown): unknown { if (typeof value !== 'string') { return value; } try { return JSON.parse(value); } catch (error) { throw new InvalidStringRecord('value is not valid JSON', value, error); } } }