refactor: improve error handling and code readability in download feature; streamline URL validation and response logic

This commit is contained in:
vchikalkin 2025-08-15 18:59:45 +03:00
parent b38a1ef2b6
commit 8df2c47e1a

View File

@ -8,7 +8,6 @@ import { Downloader } from '@tobyg74/tiktok-api-dl';
import { Composer, InputFile } from 'grammy';
const composer = new Composer<Context>();
const feature = composer.chatType('private');
const redis = getRedisInstance();
@ -17,17 +16,21 @@ feature.on('message:text', logHandle('download-message'), async (context) => {
try {
const url = context.message.text.trim();
if (!validateTikTokUrl(url)) return context.reply(context.t('invalid_url'));
if (!validateTikTokUrl(url)) {
return context.reply(context.t('invalid_url'));
}
const cachedFileId = await redis.get(url);
if (cachedFileId) return context.replyWithVideo(cachedFileId);
if (cachedFileId) {
return context.replyWithVideo(cachedFileId);
}
const { message, result } = await Downloader(url, { version: 'v3' });
if (message) {
throw new Error(message);
}
if (message) throw new Error(message);
const videoUrl = result?.videoHD || result?.videoSD || result?.videoWatermark;
const videoUrl = result?.videoSD || result?.videoWatermark;
const imagesUrls = result?.images;
if (!videoUrl && !imagesUrls?.length) {
@ -36,8 +39,8 @@ feature.on('message:text', logHandle('download-message'), async (context) => {
if (result?.type === 'video' && videoUrl) {
const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl }));
await redis.set(url, video.file_id, 'EX', TTL);
return;
}
if (result?.type === 'image' && imagesUrls) {
@ -47,7 +50,6 @@ feature.on('message:text', logHandle('download-message'), async (context) => {
}
} catch (error) {
context.logger.error(error);
return context.reply(context.t('generic'));
}
});