From 79866fb3c82e236c89b9264ce3886988621edf26 Mon Sep 17 00:00:00 2001 From: Ahyoung Ryu Date: Mon, 22 Apr 2024 11:09:41 +0900 Subject: [PATCH] feat: parse message.data safely (#155) --- src/components/ParsedBotMessageBody.tsx | 3 ++- src/components/SuggestedReplyMessageBody.tsx | 3 ++- src/utils/messages.ts | 10 +++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/components/ParsedBotMessageBody.tsx b/src/components/ParsedBotMessageBody.tsx index 26ab7c20d..80e5bdcca 100644 --- a/src/components/ParsedBotMessageBody.tsx +++ b/src/components/ParsedBotMessageBody.tsx @@ -7,6 +7,7 @@ import { CodeBlock } from './CodeBlock'; import SourceContainer, { Source } from './SourceContainer'; import { useConstantState } from '../context/ConstantContext'; import { replaceWithRegex, Token, TokenType } from '../utils'; +import { parseMessageDataSafely } from '../utils/messages'; const Text = styled.div` width: inherit; @@ -47,7 +48,7 @@ type MetaData = { export default function ParsedBotMessageBody(props: Props) { const { message, tokens } = props; const { enableSourceMessage } = useConstantState(); - const data: MetaData = JSON.parse(message.data === '' ? '{}' : message.data); + const data: MetaData = parseMessageDataSafely(message.data); const sources: Source[] = Array.isArray(data['metadatas']) ? data['metadatas']?.filter((source) => source.source_type !== 'file') : []; diff --git a/src/components/SuggestedReplyMessageBody.tsx b/src/components/SuggestedReplyMessageBody.tsx index 6cae08d5c..73f618005 100644 --- a/src/components/SuggestedReplyMessageBody.tsx +++ b/src/components/SuggestedReplyMessageBody.tsx @@ -3,6 +3,7 @@ import styled from 'styled-components'; import { BodyComponent } from './MessageComponent'; import { SuggestedReply } from '../const'; +import { parseMessageDataSafely } from '../utils/messages'; const Root = styled(BodyComponent)` color: ${({ theme }) => theme.textColor.incomingMessage}; @@ -50,7 +51,7 @@ type Props = { export default function SuggestedReplyMessageBody(props: Props) { const { message } = props; - const data: SuggestedReply = JSON.parse(message.data ?? ''); + const data: SuggestedReply = parseMessageDataSafely(message.data); return ( {data.text} diff --git a/src/utils/messages.ts b/src/utils/messages.ts index 75124e588..b1150ad42 100644 --- a/src/utils/messages.ts +++ b/src/utils/messages.ts @@ -93,7 +93,7 @@ export function isLastMessageInStreaming(lastMessage: EveryMessage | null) { ) { return false; } - const messageMetaData = JSON.parse(lastMessage.data); + const messageMetaData = parseMessageDataSafely(lastMessage.data); return 'stream' in messageMetaData && messageMetaData.stream; } @@ -136,3 +136,11 @@ export function isStaticReplyVisible( ) ); } + +export function parseMessageDataSafely(messageData: string) { + try { + return JSON.parse(messageData === '' ? '{}' : messageData); + } catch (error) { + return {}; + } +}