48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
/**
|
|
* Заменяет все "некрасивые" значения в объекте или массиве на дефис.
|
|
* - null
|
|
* - "undefined" (строка)
|
|
* - undefined
|
|
* - пустая строка ""
|
|
*/
|
|
import dayjs from 'dayjs';
|
|
|
|
const isDateKey = (key: string): boolean => {
|
|
// Покрываем: _at, _date, _time, _seen, timestamp, last_login, date, time и т.д.
|
|
const datePatterns = /_(at|date|time|seen)$|^(date|time|timestamp|last_login)$/;
|
|
return datePatterns.test(key);
|
|
};
|
|
|
|
const formatDateValue = (value: unknown): string => {
|
|
if (typeof value !== 'string' || value === '-' || value === '') return value as string;
|
|
const d = dayjs(value);
|
|
if (!d.isValid()) return value;
|
|
if (value.includes('T') || value.length > 10) {
|
|
return d.format('DD.MM.YYYY HH:mm');
|
|
}
|
|
return d.format('DD.MM.YYYY');
|
|
};
|
|
|
|
export const normalizeData = <T>(data: T): T => {
|
|
if (data === null || data === undefined || data === 'undefined' || data === '') {
|
|
return '-' as unknown as T;
|
|
}
|
|
|
|
if (Array.isArray(data)) {
|
|
return data.map(item => normalizeData(item)) as unknown as T;
|
|
}
|
|
|
|
if (typeof data === 'object' && data !== null) {
|
|
const result: Record<string, any> = {};
|
|
for (const [key, value] of Object.entries(data)) {
|
|
let normalized = normalizeData(value);
|
|
if (isDateKey(key) && typeof normalized === 'string' && normalized !== '-') {
|
|
normalized = formatDateValue(normalized);
|
|
}
|
|
result[key] = normalized;
|
|
}
|
|
return result as T;
|
|
}
|
|
|
|
return data;
|
|
}; |