Skip to content

Commit

Permalink
feat: parse message.data safely (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
AhyoungRyu authored Apr 22, 2024
1 parent c0cd04c commit 79866fb
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/components/ParsedBotMessageBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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')
: [];
Expand Down
3 changes: 2 additions & 1 deletion src/components/SuggestedReplyMessageBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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 (
<Root>
<Text>{data.text}</Text>
Expand Down
10 changes: 9 additions & 1 deletion src/utils/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -136,3 +136,11 @@ export function isStaticReplyVisible(
)
);
}

export function parseMessageDataSafely(messageData: string) {
try {
return JSON.parse(messageData === '' ? '{}' : messageData);
} catch (error) {
return {};
}
}

0 comments on commit 79866fb

Please sign in to comment.