Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: replaceTextProperties #101

Merged
merged 1 commit into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/hooks/useFetch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import replaceTextProperties from '@/utils/extractInnermostValues';
import { useEffect, useState } from 'react';
import { xml2json } from 'xml-js';

Expand All @@ -17,7 +18,7 @@ export default function useFetch<T>(url: string) {
const response = await fetch(url);
const xmlText = await response.text();
const jsonData = JSON.parse(xml2json(xmlText, { compact: true, spaces: 2 }));
setData(jsonData);
setData(replaceTextProperties<T>(jsonData));
} catch (error) {
console.error('Error fetching data:', error);
} finally {
Expand Down
35 changes: 35 additions & 0 deletions src/utils/extractInnermostValues.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* ๊ฐ์ฒด์˜ '_text' ์†์„ฑ์„ ํ•ด๋‹น ๊ฐ’์œผ๋กœ ๋Œ€์ฒดํ•˜๋Š” ํ•จ์ˆ˜
*
* @template T - ์ž…๋ ฅ ๊ฐ์ฒด์˜ ํƒ€์ž…
* @param {T} obj - ๊ฐ€์žฅ ์•ˆ์ชฝ์˜ ๊ฐ’์„ ์ถ”์ถœํ•  ๊ฐ์ฒด
* @returns {T} '_text' ์†์„ฑ์ด ํ•ด๋‹น ๊ฐ’์œผ๋กœ ๋Œ€์ฒด๋œ ์ž…๋ ฅ ๊ฐ์ฒด์™€ ๋™์ผํ•œ ๊ตฌ์กฐ์˜ ์ƒˆ๋กœ์šด ๊ฐ์ฒด
*/
export default function replaceTextProperties<T>(obj: T): T {
if (typeof obj !== 'object' || obj === null) {
return obj;
}

if (Array.isArray(obj)) {
return obj.map(replaceTextProperties) as unknown as T;
}

if (obj && typeof obj === 'object' && '_text' in obj) {
const textValue = obj._text;
if (typeof textValue === 'string') {
const parsedValue = +textValue;
if (!isNaN(parsedValue)) {
return parsedValue as T;
}
}
return textValue as T;
}

const result: { [key: string]: T[keyof T] } = {};

for (const [key, value] of Object.entries(obj)) {
result[key] = replaceTextProperties(value);
}

return result as T;
}
Loading