73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
import { readBody } from 'h3';
|
|
import { query } from '~/utils/db';
|
|
import { useResponseError, useResponseSuccess } from '~/utils/response';
|
|
import { testTelegramConfig } from '~/utils/telegram-bot';
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const body = await readBody(event);
|
|
|
|
if (!body?.name || !body?.botToken || !body?.chatId) {
|
|
return useResponseError('缺少必填字段', -1);
|
|
}
|
|
|
|
const notificationTypes = Array.isArray(body.notificationTypes)
|
|
? body.notificationTypes
|
|
: ['transaction'];
|
|
|
|
// 测试配置是否有效
|
|
const testResult = await testTelegramConfig(body.botToken, body.chatId);
|
|
if (!testResult.success) {
|
|
return useResponseError(
|
|
`Telegram配置测试失败: ${testResult.error}`,
|
|
-1,
|
|
);
|
|
}
|
|
|
|
const now = new Date().toISOString();
|
|
|
|
const { rows } = await query<{
|
|
id: number;
|
|
name: string;
|
|
bot_token: string;
|
|
chat_id: string;
|
|
notification_types: string;
|
|
is_enabled: boolean;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}>(
|
|
`INSERT INTO telegram_notification_configs (
|
|
name,
|
|
bot_token,
|
|
chat_id,
|
|
notification_types,
|
|
is_enabled,
|
|
created_at,
|
|
updated_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
RETURNING id, name, bot_token, chat_id, notification_types, is_enabled, created_at, updated_at`,
|
|
[
|
|
body.name,
|
|
body.botToken,
|
|
body.chatId,
|
|
JSON.stringify(notificationTypes),
|
|
body.isEnabled !== false,
|
|
now,
|
|
now,
|
|
],
|
|
);
|
|
|
|
const row = rows[0];
|
|
|
|
return useResponseSuccess({
|
|
id: row.id,
|
|
name: row.name,
|
|
botToken: row.bot_token,
|
|
chatId: row.chat_id,
|
|
notificationTypes,
|
|
isEnabled: row.is_enabled,
|
|
createdAt: row.created_at,
|
|
updatedAt: row.updated_at,
|
|
});
|
|
});
|