livechat-widget
Version:
LiveChat Widget for Next.js applications
117 lines (106 loc) • 3.87 kB
text/typescript
import { ChatMessage, ChatRoom } from '@/types/chat';
// เปลี่ยนจากค่าคงที่เป็นตัวแปรที่สามารถกำหนดได้
let API_BASE_URL = '';
// เพิ่มฟังก์ชันสำหรับกำหนด API_BASE_URL
export function setApiBaseUrl(url: string): void {
API_BASE_URL = url;
}
export async function fetchMessages(roomCode: string, appId: string, limit: number = 50): Promise<ChatMessage[]> {
try {
const response = await fetch(
`${API_BASE_URL}/chat/rooms/${roomCode}/apps/${appId}/messages?limit=${limit}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
// ถ้า API ยังไม่พร้อมใช้งาน ให้ส่งค่า array ว่างกลับไป
if (response.status === 404 || response.status === 500) {
console.warn(`API not available: ${response.status}. Returning empty array.`);
return [];
}
throw new Error(`Error fetching messages: ${response.status}`);
}
const data = await response.json();
return Array.isArray(data.payload?.messages) ? data.payload.messages : [];
} catch (error) {
console.error('Failed to fetch messages:', error);
// ส่งค่า array ว่างกลับไปเมื่อเกิดข้อผิดพลาด
return [];
}
}
export async function sendMessage(message: ChatMessage): Promise<void> {
try {
const response = await fetch(`${API_BASE_URL}/chat/messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_info: message.user_info,
user_code: message.user_code,
app_id: message.app_id,
room_code: message.room_code,
message: message.content
}),
});
if (!response.ok) {
console.warn(`Error sending message: ${response.status}`);
// ไม่ throw error เพื่อให้แอปทำงานต่อได้
return;
}
} catch (error) {
console.error('Failed to send message:', error);
// ไม่ throw error เพื่อให้แอปทำงานต่อได้
}
}
export async function getOrCreateRoom(roomCode: string, appId: string, name: string): Promise<ChatRoom> {
try {
const response = await fetch(`${API_BASE_URL}/room`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
room_code: roomCode,
app_id: appId,
name: name,
}),
});
if (!response.ok) {
console.warn(`Error creating/getting room: ${response.status}`);
// ส่งค่า default กลับไปเพื่อให้แอปทำงานต่อได้
return {
id: 'mock-room-id',
roomCode,
appId,
name,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
}
const data = await response.json();
return data.payload?.room || {
id: 'mock-room-id',
roomCode,
appId,
name,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
} catch (error) {
console.error('Failed to create/get room:', error);
// ส่งค่า default กลับไปเพื่อให้แอปทำงานต่อได้
return {
id: 'mock-room-id',
roomCode,
appId,
name,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
}
}