Files
super-app/App/common/utilities/SerializerUtil.ts
2024-03-27 15:06:03 +00:00

43 lines
1.3 KiB
TypeScript

import { logToSentry } from "../hooks/useSentryLogging";
export function parseValue(value: any, targetType: string): any | null {
if (targetType === "string") {
return String(value);
} else if (targetType === "number") {
return Number(value);
} else if (targetType === "object") {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch (error) {
logToSentry(
`Error parsing JSON: ${value} | Error: ${error} | MethodName: ${arguments.callee.name}`
);
return null;
}
} else {
logToSentry(
`Value is not a string; cannot parse as object: ${value} | MethodName: ${arguments.callee.name}`
);
return null;
}
} else {
logToSentry(
`Invalid targetType: ${targetType} | MethodName: ${arguments.callee.name}`
);
return null;
}
}
// Usage examples:
// const stringValue: string = '123';
// const numberValue: number = 456;
// const objectValue: string = '{"key": "value"}';
// const parsedString: string = parseValue(stringValue, 'string');
// const parsedNumber: number = parseValue(numberValue, 'number');
// const parsedObject: object | null = parseValue(objectValue, 'object');
// console.log(parsedString); // "123"
// console.log(parsedNumber); // 456
// console.log(parsedObject); // { key: 'value' }