Skip to content

Commit

Permalink
chore:handle non json error
Browse files Browse the repository at this point in the history
  • Loading branch information
KannuSingh committed Jan 23, 2025
1 parent 536756b commit e1070f1
Showing 1 changed file with 58 additions and 42 deletions.
100 changes: 58 additions & 42 deletions advanced/dapps/chat-demo-agent/src/lib/chatApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,51 +19,35 @@ interface BasicResponse {

type SendMessageApiResponse = SwapResponse | BasicResponse;

export const sendChatMessageToApi = async (
messageWithContext: MessageWithContext
): Promise<{ message: string }> => {
try {
const API_URL = '/api/send-message';
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(messageWithContext),
});

if (!response.ok) {
const errorData = await response.json();
const errorMessage = errorData.message || `Failed to get response from server: ${response.status}`;
throw new Error(errorMessage);
}
// Generic function to fetch API with type-safe body
const fetchApi = async <T extends object>(
url: string,
body: T
): Promise<Response> => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});

const data: SendMessageApiResponse = await response.json();

// Handle response with a transaction link
if ('txLink' in data) {
const statusMessage = data.txLink && data.userOpHash
? `\n${hiddenTruncateUserOpHash(data.userOpHash)}View details: ${formatLink('Transaction Link', data.txLink)}`
: data.status === 'pending' && data.userOpHash
? `\nYou can check the status later using the purchase id: ${truncateUserOpHash(data.userOpHash)}`
: '';

return {
message: `${data.message}${statusMessage}`
};
}
if (!response.ok) {
throw new Error(await parseErrorResponse(response));
}

// Handle basic response
return {
message: data.message
};
return response;
};

} catch (error) {
throw new Error(
error instanceof Error
? error.message
: 'Failed to send message: Unknown error'
);
const parseErrorResponse = async (response: Response): Promise<string> => {
const errorMessage = `Failed to get response from server: ${response.status}`;

try {
const errorData = await response.json();
return errorData.message || errorMessage;
} catch {
const errorText = await response.text();
return errorText || errorMessage;
}
};

Expand All @@ -75,3 +59,35 @@ const truncateUserOpHash = (hash: string) => `<span onclick="navigator.clipboard

// Helper function to truncate hash
const hiddenTruncateUserOpHash = (hash: string) => `<span class="hidden" title="PurchaseId" >${hash}</span>`;

const formatApiResponse = (data: SendMessageApiResponse): { message: string } => {
let statusMessage = '';

if ('txLink' in data) {
statusMessage = data.txLink && data.userOpHash
? `\n${hiddenTruncateUserOpHash(data.userOpHash)}View details: ${formatLink('Transaction Link', data.txLink)}`
: data.status === 'pending' && data.userOpHash
? `\nYou can check the status later using the purchase id: ${truncateUserOpHash(data.userOpHash)}`
: '';
}

return { message: `${data.message}${statusMessage}` };
};


// Main function to send chat message to the API
export const sendChatMessageToApi = async (
messageWithContext: MessageWithContext
): Promise<{ message: string }> => {
const API_URL = '/api/send-message';

try {
const response = await fetchApi(API_URL, messageWithContext);
const data: SendMessageApiResponse = await response.json();
return formatApiResponse(data);
} catch (error) {
throw new Error(
error instanceof Error ? error.message : 'Failed to send message: Unknown error'
);
}
};

0 comments on commit e1070f1

Please sign in to comment.