Загрузка данных


import { ChartSeriesType, Intervals, IntervalsToTimeframe, SymbolInfo, TimeFormat } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { DateFormat } from '@src/utils';

export interface ChartSettings {
  symbolInfo: SymbolInfo;
  timeframe: Timeframes;
  seriesSelected: ChartSeriesType;
  timeFormat: TimeFormat;
  dateFormat: DateFormat;
  interval: Intervals | null;
}

export type ChartSettingsSource = Partial<ChartSettings> | string;

function parseJsonIfString(value: unknown): unknown {
  if (typeof value !== 'string') return value;
  try {
    return JSON.parse(value);
  } catch {
    return undefined;
  }
}

function asPlainObject(value: unknown): Record<string, unknown> | undefined {
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
  return value as Record<string, unknown>;
}

function asString(value: unknown): string | undefined {
  return typeof value === 'string' ? value : undefined;
}

function asStringList(value: unknown): string[] | undefined {
  if (!Array.isArray(value)) return undefined;

  return value.map(asString).filter((val) => val !== undefined);
}

function asInterval(value: unknown): Intervals | null | undefined {
  if (value === null) return null;

  const intervalString = asString(value);
  if (intervalString === undefined) return undefined;

  return intervalString in IntervalsToTimeframe ? (intervalString as Intervals) : undefined;
}

export function parseChartSettings(value: unknown): Partial<ChartSettings> {
  const parsedValue = parseJsonIfString(value);
  const settingsObject = asPlainObject(parsedValue);

  if (!settingsObject) return {};

  return {
    timeframe: asString(settingsObject.timeframe) as Timeframes | undefined,
    seriesSelected: asString(settingsObject.seriesSelected) as ChartSeriesType | undefined,
    symbol: asString(settingsObject.symbol),
    timeFormat: asString(settingsObject.timeFormat) as TimeFormat | undefined,
    dateFormat: asString(settingsObject.dateFormat) as DateFormat | undefined,
    interval: asInterval(settingsObject.interval),
  };
}