45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { TelegramMessage } from '@/app/types'
|
|
|
|
export const sendMessage = async (data: TelegramMessage) => {
|
|
const API_URL = process.env.NEXT_PUBLIC_API_URL
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
}
|
|
|
|
try {
|
|
const body = JSON.stringify({
|
|
source: data.source,
|
|
name: data.name,
|
|
phone_number: data.phone_number,
|
|
message: data.message,
|
|
})
|
|
|
|
const response = await fetch(`${API_URL}/send-message/`, {
|
|
method: 'POST',
|
|
headers,
|
|
body,
|
|
})
|
|
|
|
if (!response.ok) {
|
|
let errorMessage = `Failed to send form data: ${response.status} ${response.statusText}`
|
|
try {
|
|
const errorData = await response.text()
|
|
|
|
if (errorData) {
|
|
errorMessage += ` - ${errorData}`
|
|
}
|
|
} catch (e) {
|
|
console.error('Error parsing error response:', e)
|
|
}
|
|
throw new Error(errorMessage)
|
|
}
|
|
const text = await response.text()
|
|
return text ? JSON.parse(text) : null
|
|
} catch (error) {
|
|
console.error('Error sending form data:', error)
|
|
throw error
|
|
}
|
|
}
|