Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(api): typed platform errors and the request signal in platform calls

spacesdrivec4abee8f8fe6
diff --git a/backend/middleware/requestContext.ts b/backend/middleware/requestContext.ts
index 9a69d32..6140be4 100644
--- a/backend/middleware/requestContext.ts
+++ b/backend/middleware/requestContext.ts
@@ -28,4 +28,4 @@ export function requestLogger(c: AppContext): Logger {
// what a controller hands to services: request metadata without any Hono type
export function requestContextOf(c: AppContext): RequestContext {
return { requestId: c.get('requestId'), signal: c.get('signal'), log: requestLogger(c) };
-}
+}
\ No newline at end of file
diff --git a/backend/services/instagram/instagramApi.ts b/backend/services/instagram/instagramApi.ts
index daa3049..44a47de 100644
--- a/backend/services/instagram/instagramApi.ts
+++ b/backend/services/instagram/instagramApi.ts
@@ -1,3 +1,4 @@
+import { UpstreamError, UpstreamTimeoutError } from '../../lib/errors.ts';
import type { InstagramContainerStatusCode, InstagramProfile } from '../../../shared/types/instagram.ts';
const IG_GRAPH_URL = 'https://graph.instagram.com';
@@ -56,45 +57,66 @@ function buildGraphUrl(endpoint: string, params: GraphParams): URL {
}
function isTransientError(err: Error): boolean | undefined {
- return err.name === 'AbortError' ||
+ return err.name === 'AbortError' || err.name === 'TimeoutError' ||
err.message?.includes('EAI_AGAIN') ||
err.message?.includes('ECONNRESET');
}
-function readGraphResponse<T>(data: T & InstagramApiErrorBody): T {
- if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));
- if (data.error_message) throw new Error(data.error_message);
+export function readGraphResponse<T>(data: T & InstagramApiErrorBody): T {
+ if (data.error) {
+ throw new UpstreamError(data.error.message || data.error.error_message || JSON.stringify(data.error), { status: data.error.code });
+ }
+ if (data.error_message) throw new UpstreamError(data.error_message);
return data;
}
-export async function igFetch<T = unknown>(endpoint: string, params: GraphParams = {}, retries = 1): Promise<T> {
+function unreachable(err: unknown): Error {
+ return new UpstreamError(`Instagram API unreachable (${(err as Error).message})`, { cause: err });
+}
+
+// GET with a 15 second timeout and one retry on a network blip; a cancelled request is never retried
+export async function igFetch<T = unknown>(endpoint: string, params: GraphParams = {}, retries = 1, signal?: AbortSignal): Promise<T> {
const url = buildGraphUrl(endpoint, params);
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
let response: Response;
try {
- response = await fetch(url.toString(), { signal: controller.signal });
+ response = await fetch(url.toString(), { signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
} catch (err) {
- clearTimeout(timer);
+ if (signal?.aborted) throw new UpstreamTimeoutError('Instagram', err);
if (isTransientError(err as Error) && retries > 0) {
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
- return igFetch<T>(endpoint, params, retries - 1);
+ return igFetch<T>(endpoint, params, retries - 1, signal);
}
- if ((err as Error).name === 'AbortError') throw new Error('Instagram API request timed out');
- throw new Error(`Instagram API unreachable (${(err as Error).message})`);
+ if ((err as Error).name === 'AbortError' || (err as Error).name === 'TimeoutError') throw new UpstreamTimeoutError('Instagram', err);
+ throw unreachable(err);
}
- clearTimeout(timer);
return readGraphResponse(await response.json() as T & InstagramApiErrorBody);
}
-export async function fetchInstagramProfile(igUserId: string | null | undefined, accessToken: string): Promise<InstagramProfile> {
+// POST is never retried: a repeated media_publish could publish the post twice
+export async function igPost<T = unknown>(endpoint: string, params: GraphParams, signal?: AbortSignal): Promise<T> {
+ const url = buildGraphUrl(endpoint, params);
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
+ let response: Response;
+ try {
+ response = await fetch(url.toString(), { method: 'POST', signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
+ } catch (err) {
+ if (signal?.aborted || (err as Error).name === 'AbortError' || (err as Error).name === 'TimeoutError') {
+ throw new UpstreamTimeoutError('Instagram', err);
+ }
+ throw unreachable(err);
+ }
+ return readGraphResponse(await response.json() as T & InstagramApiErrorBody);
+}
+
+export async function fetchInstagramProfile(igUserId: string | null | undefined, accessToken: string, signal?: AbortSignal): Promise<InstagramProfile> {
const endpoint = igUserId ? `/${igUserId}` : '/me';
const data = await igFetch<InstagramApiProfile>(endpoint, {
access_token: accessToken,
fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',
- });
+ }, 1, signal);
return {
igUserId: data.user_id || data.id || igUserId,
name: data.name || '',
diff --git a/backend/services/instagram/instagramMedia.ts b/backend/services/instagram/instagramMedia.ts
index e01e2d5..c4a77ae 100644
--- a/backend/services/instagram/instagramMedia.ts
+++ b/backend/services/instagram/instagramMedia.ts
@@ -1,4 +1,5 @@
import { igFetch } from './instagramApi.ts';
+import { UpstreamTimeoutError } from '../../lib/errors.ts';
import type { GraphParams } from './instagramApi.ts';
import type { InstagramContentType, InstagramMedia } from '../../../shared/types/instagram.ts';
@@ -75,14 +76,17 @@ export function normalizeInstagramMedia(raw: InstagramApiMedia): InstagramMedia
};
}
-async function fetchMediaPage(igUserId: string, accessToken: string, after: string | null | undefined): Promise<InstagramApiMediaPage> {
+async function fetchMediaPage(
+ igUserId: string, accessToken: string, after: string | null | undefined, signal?: AbortSignal,
+): Promise<InstagramApiMediaPage> {
const params: GraphParams = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };
if (after) params.after = after;
try {
- return await igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });
- } catch {
+ return await igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` }, 1, signal);
+ } catch (err) {
+ if (err instanceof UpstreamTimeoutError) throw err;
// one item without insights (e.g. pre-professional posts) fails the whole page
- return igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });
+ return igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS }, 1, signal);
}
}
@@ -94,12 +98,12 @@ function uniqueById(items: InstagramApiMedia[]): InstagramApiMedia[] {
return [...unique.values()];
}
-export async function fetchInstagramMedia(igUserId: string, accessToken: string, limit = 500): Promise<InstagramMedia[]> {
+export async function fetchInstagramMedia(igUserId: string, accessToken: string, limit = 500, signal?: AbortSignal): Promise<InstagramMedia[]> {
const allMedia: InstagramApiMedia[] = [];
let after: string | null | undefined = null;
for (let page = 0; page < MAX_MEDIA_PAGES && allMedia.length < limit; page++) {
- const data = await fetchMediaPage(igUserId, accessToken, after);
+ const data = await fetchMediaPage(igUserId, accessToken, after, signal);
if (Array.isArray(data.data)) allMedia.push(...data.data);
after = data.paging?.next ? data.paging?.cursors?.after : null;
if (!after) break;
diff --git a/backend/services/instagram/instagramTokens.ts b/backend/services/instagram/instagramTokens.ts
index 2fdc85e..1617ef6 100644
--- a/backend/services/instagram/instagramTokens.ts
+++ b/backend/services/instagram/instagramTokens.ts
@@ -1,5 +1,6 @@
import { getAccounts, updateAccount } from '../../lib/db.ts';
import { igFetch } from './instagramApi.ts';
+import { UpstreamError } from '../../lib/errors.ts';
import type { Account } from '../../../shared/types/domain.ts';
import type { SupabaseClient } from '../../types/app.ts';
@@ -29,22 +30,22 @@ function toTokenResult(data: IssuedToken): InstagramTokenResult {
};
}
-export async function exchangeForLongLivedToken(shortToken: string, appSecret: string): Promise<InstagramTokenResult> {
+export async function exchangeForLongLivedToken(shortToken: string, appSecret: string, signal?: AbortSignal): Promise<InstagramTokenResult> {
const data = await igFetch<InstagramApiToken>('/access_token', {
grant_type: 'ig_exchange_token',
client_secret: appSecret,
access_token: shortToken,
- });
- if (!data.access_token) throw new Error('Failed to exchange token - check Instagram App Secret');
+ }, 1, signal);
+ if (!data.access_token) throw new UpstreamError('Failed to exchange token - check Instagram App Secret');
return toTokenResult(data as IssuedToken);
}
-export async function refreshLongLivedToken(longToken: string): Promise<InstagramTokenResult> {
+export async function refreshLongLivedToken(longToken: string, signal?: AbortSignal): Promise<InstagramTokenResult> {
const data = await igFetch<InstagramApiToken>('/refresh_access_token', {
grant_type: 'ig_refresh_token',
access_token: longToken,
- });
- if (!data.access_token) throw new Error('Failed to refresh token');
+ }, 1, signal);
+ if (!data.access_token) throw new UpstreamError('Failed to refresh token');
return toTokenResult(data as IssuedToken);
}
diff --git a/backend/services/reddit/redditApi.ts b/backend/services/reddit/redditApi.ts
index 38bb159..2c5230a 100644
--- a/backend/services/reddit/redditApi.ts
+++ b/backend/services/reddit/redditApi.ts
@@ -1,4 +1,5 @@
import type { RedditMediaType, RedditPost, RedditProfile, RedditTrackedPostData } from '../../../shared/types/reddit.ts';
+import { NotFoundError, UpstreamError, UpstreamTimeoutError, ValidationError, isAbortError } from '../../lib/errors.ts';
export { computeRedditAnalytics } from './redditAnalytics.ts';
@@ -62,23 +63,29 @@ interface RedditListing<T> {
type RedditCookie = string | null | undefined;
-async function redditFetch<T>(path: string, cookie: RedditCookie): Promise<T> {
+async function redditFetch<T>(path: string, cookie: RedditCookie, signal?: AbortSignal): Promise<T> {
const headers: Record<string, string> = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };
if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
- const res = await fetch(`${REDDIT_BASE}${path}`, { headers });
+ let res: Response;
+ try {
+ res = await fetch(`${REDDIT_BASE}${path}`, { headers, signal });
+ } catch (err) {
+ if (isAbortError(err)) throw new UpstreamTimeoutError('Reddit', err);
+ throw new UpstreamError(`Reddit could not be reached (${(err as Error).message})`, { cause: err });
+ }
- if (res.status === 404) throw new Error('Reddit user not found - check the username');
- if (res.status === 403) throw new Error('Session cookie is invalid or expired - open reddit.com in your browser, copy a fresh reddit_session value from DevTools (Application > Cookies > reddit.com), delete this account, and re-add it');
- if (res.status === 429) throw new Error('Reddit rate limit hit - try again in a moment');
- if (!res.ok) throw new Error(`Reddit API ${res.status}: ${res.statusText}`);
+ if (res.status === 404) throw new NotFoundError('Reddit user not found - check the username');
+ if (res.status === 403) throw new UpstreamError('Session cookie is invalid or expired - open reddit.com in your browser, copy a fresh reddit_session value from DevTools (Application > Cookies > reddit.com), delete this account, and re-add it', { status: 403 });
+ if (res.status === 429) throw new UpstreamError('Reddit rate limit hit - try again in a moment', { status: 429 });
+ if (!res.ok) throw new UpstreamError(`Reddit API ${res.status}: ${res.statusText}`, { status: res.status });
const data = await res.json() as T & RedditApiError;
- if (data.error) throw new Error(data.message || 'Reddit API error');
+ if (data.error) throw new UpstreamError(data.message || 'Reddit API error');
return data;
}
-export async function fetchRedditProfile(username: string, cookie: RedditCookie): Promise<RedditProfile> {
- const data = await redditFetch<RedditThing<RedditApiUser>>(`/user/${username}/about.json`, cookie);
+export async function fetchRedditProfile(username: string, cookie: RedditCookie, signal?: AbortSignal): Promise<RedditProfile> {
+ const data = await redditFetch<RedditThing<RedditApiUser>>(`/user/${username}/about.json`, cookie, signal);
const user = data.data;
return {
username: user.name,
@@ -124,7 +131,7 @@ function normalizeRedditPost(post: RedditApiPost): RedditPost {
};
}
-export async function fetchRedditPosts(username: string, cookie: RedditCookie, limit = 100): Promise<RedditPost[]> {
+export async function fetchRedditPosts(username: string, cookie: RedditCookie, limit = 100, signal?: AbortSignal): Promise<RedditPost[]> {
const allPosts: RedditApiPost[] = [];
let after: string | null = null;
let pages = 0;
@@ -136,7 +143,7 @@ export async function fetchRedditPosts(username: string, cookie: RedditCookie, l
});
if (after) query.set('after', after);
- const data: RedditListing<RedditApiPost> = await redditFetch<RedditListing<RedditApiPost>>(`/user/${username}/submitted.json?${query}`, cookie);
+ const data: RedditListing<RedditApiPost> = await redditFetch<RedditListing<RedditApiPost>>(`/user/${username}/submitted.json?${query}`, cookie, signal);
const children = data.data?.children ?? [];
if (children.length === 0) break;
@@ -154,20 +161,20 @@ function parseRedditPostUrl(rawUrl: string): string {
try {
parsedUrl = new URL(rawUrl);
} catch {
- throw new Error('Invalid URL - paste the full post link from reddit.com');
+ throw new ValidationError('Invalid URL - paste the full post link from reddit.com');
}
- if (!parsedUrl.hostname.includes('reddit.com')) throw new Error('Not a Reddit URL - paste a link from reddit.com');
+ if (!parsedUrl.hostname.includes('reddit.com')) throw new ValidationError('Not a Reddit URL - paste a link from reddit.com');
const match = parsedUrl.pathname.match(/^(\/r\/[^/]+\/comments\/[^/]+(?:\/[^/]+)?)\/?$/);
- if (!match) throw new Error('Not a Reddit post URL - paste the full post link including /r/.../comments/...');
+ if (!match) throw new ValidationError('Not a Reddit post URL - paste the full post link including /r/.../comments/...');
return match[1];
}
-export async function fetchTrackedPostData(postUrl: string, cookie: RedditCookie): Promise<RedditTrackedPostData> {
+export async function fetchTrackedPostData(postUrl: string, cookie: RedditCookie, signal?: AbortSignal): Promise<RedditTrackedPostData> {
const path = parseRedditPostUrl(postUrl);
- const data = await redditFetch<RedditListing<RedditApiPost>[]>(`${path}.json`, cookie);
- if (!Array.isArray(data) || !data[0]) throw new Error('Unexpected Reddit response - post may be deleted or private');
+ const data = await redditFetch<RedditListing<RedditApiPost>[]>(`${path}.json`, cookie, signal);
+ if (!Array.isArray(data) || !data[0]) throw new UpstreamError('Unexpected Reddit response - post may be deleted or private');
const post = data[0]?.data?.children?.[0]?.data;
- if (!post) throw new Error('Post not found or has been deleted');
+ if (!post) throw new NotFoundError('Post not found or has been deleted');
return {
postId: post.id,
title: post.title,
diff --git a/backend/services/youtube/youtubeApi.ts b/backend/services/youtube/youtubeApi.ts
index d0e1862..8e2d750 100644
--- a/backend/services/youtube/youtubeApi.ts
+++ b/backend/services/youtube/youtubeApi.ts
@@ -1,3 +1,5 @@
+import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
+
export type YouTubeApiParams = Record<string, string>;
export interface YouTubeApiThumbnail {
@@ -22,11 +24,6 @@ export interface YouTubeApiErrorBody {
};
}
-export interface YouTubeApiError extends Error {
- reason?: string;
- status?: number;
-}
-
export interface YouTubeApiChannel {
id: string;
snippet: {
@@ -91,17 +88,20 @@ export interface YouTubeApiVideo {
}
// adds the key to the caller's params object, as callers always pass a fresh one
-export async function ytFetch<T>(endpoint: string, params: YouTubeApiParams, apiKey: string): Promise<T> {
+export async function ytFetch<T>(endpoint: string, params: YouTubeApiParams, apiKey: string, signal?: AbortSignal): Promise<T> {
const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
params.key = apiKey;
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
- const response = await fetch(url.toString());
+ let response: Response;
+ try {
+ response = await fetch(url.toString(), { signal });
+ } catch (err) {
+ if (isAbortError(err)) throw new UpstreamTimeoutError('YouTube', err);
+ throw new UpstreamError(`YouTube could not be reached (${(err as Error).message})`, { cause: err });
+ }
const data = await response.json() as T & YouTubeApiErrorBody;
if (data.error) {
- const err: YouTubeApiError = new Error(data.error.message);
- err.reason = data.error.errors?.[0]?.reason || '';
- err.status = data.error.code;
- throw err;
+ throw new UpstreamError(data.error.message, { reason: data.error.errors?.[0]?.reason || '', status: data.error.code });
}
return data;
}
diff --git a/backend/services/youtube/youtubeChannels.ts b/backend/services/youtube/youtubeChannels.ts
index 670bd28..fda83ee 100644
--- a/backend/services/youtube/youtubeChannels.ts
+++ b/backend/services/youtube/youtubeChannels.ts
@@ -1,4 +1,5 @@
import { ytFetch } from './youtubeApi.ts';
+import { NotFoundError, UpstreamTimeoutError, ValidationError } from '../../lib/errors.ts';
import type { YouTubeApiParams, YouTubeApiListResponse, YouTubeApiChannel, YouTubeApiSearchResult } from './youtubeApi.ts';
import type { YouTubeChannelData } from '../../../shared/types/youtube.ts';
@@ -22,45 +23,46 @@ function extractChannelId(input: string | null | undefined): string | null {
return trimmed;
}
-// null when the lookup finds nothing or fails, so the next strategy runs
+// null when the lookup finds nothing or fails, so the next strategy runs; a timeout stops the search
async function lookupChannelId<TItem>(
- endpoint: string, params: YouTubeApiParams, pickId: (item: TItem) => string, apiKey: string,
+ endpoint: string, params: YouTubeApiParams, pickId: (item: TItem) => string, apiKey: string, signal?: AbortSignal,
): Promise<string | null> {
try {
- const data = await ytFetch<YouTubeApiListResponse<TItem>>(endpoint, params, apiKey);
+ const data = await ytFetch<YouTubeApiListResponse<TItem>>(endpoint, params, apiKey, signal);
if (data.items && data.items.length > 0) return pickId(data.items[0]);
return null;
- } catch {
+ } catch (err) {
+ if (err instanceof UpstreamTimeoutError) throw err;
return null;
}
}
-export async function resolveChannelId(input: string | null | undefined, apiKey: string): Promise<string> {
+export async function resolveChannelId(input: string | null | undefined, apiKey: string, signal?: AbortSignal): Promise<string> {
const extracted = extractChannelId(input);
- if (!extracted) throw new Error('Invalid input');
+ if (!extracted) throw new ValidationError('Invalid input');
if (CHANNEL_ID_PATTERN.test(extracted)) return extracted;
// sequential on purpose: a search costs 100 quota units
- const byHandle = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);
+ const byHandle = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey, signal);
if (byHandle !== null) return byHandle;
- const byUsername = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);
+ const byUsername = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey, signal);
if (byUsername !== null) return byUsername;
const searchParams = { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' };
- const bySearch = await lookupChannelId<YouTubeApiSearchResult>('search', searchParams, (item) => item.snippet.channelId, apiKey);
+ const bySearch = await lookupChannelId<YouTubeApiSearchResult>('search', searchParams, (item) => item.snippet.channelId, apiKey, signal);
if (bySearch !== null) return bySearch;
- throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
+ throw new NotFoundError('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
}
-export async function fetchChannelData(channelId: string, apiKey: string): Promise<YouTubeChannelData> {
+export async function fetchChannelData(channelId: string, apiKey: string, signal?: AbortSignal): Promise<YouTubeChannelData> {
const data = await ytFetch<YouTubeApiListResponse<YouTubeApiChannel>>('channels', {
part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',
id: channelId,
- }, apiKey);
+ }, apiKey, signal);
- if (!data.items || data.items.length === 0) throw new Error('Channel not found');
+ if (!data.items || data.items.length === 0) throw new NotFoundError('Channel not found');
const channel = data.items[0];
return {
diff --git a/backend/services/youtube/youtubeTracked.ts b/backend/services/youtube/youtubeTracked.ts
index 971aa8e..ddd1a7b 100644
--- a/backend/services/youtube/youtubeTracked.ts
+++ b/backend/services/youtube/youtubeTracked.ts
@@ -1,4 +1,5 @@
import { ytFetch, optionalCount } from './youtubeApi.ts';
+import { NotFoundError, ValidationError } from '../../lib/errors.ts';
import type { YouTubeApiListResponse, YouTubeApiVideo } from './youtubeApi.ts';
import type { YouTubeTrackedVideoData } from '../../../shared/types/youtube.ts';
@@ -21,16 +22,16 @@ export function extractYouTubeVideoId(url: string): string | null {
return searchParams.get('v');
}
-export async function fetchTrackedYouTubeData(videoUrl: string, apiKey: string): Promise<YouTubeTrackedVideoData> {
+export async function fetchTrackedYouTubeData(videoUrl: string, apiKey: string, signal?: AbortSignal): Promise<YouTubeTrackedVideoData> {
const videoId = extractYouTubeVideoId(videoUrl);
- if (!videoId) throw new Error('Invalid YouTube URL - could not extract video ID');
+ if (!videoId) throw new ValidationError('Invalid YouTube URL - could not extract video ID');
const data = await ytFetch<YouTubeApiListResponse<TrackedApiVideo>>('videos', {
part: 'snippet,statistics',
id: videoId,
- }, apiKey);
+ }, apiKey, signal);
- if (!data.items || data.items.length === 0) throw new Error('YouTube video not found - check the URL');
+ if (!data.items || data.items.length === 0) throw new NotFoundError('YouTube video not found - check the URL');
const { snippet, statistics } = data.items[0];
const isShort = videoUrl.includes('/shorts/');
diff --git a/backend/services/youtube/youtubeVideos.ts b/backend/services/youtube/youtubeVideos.ts
index d862e38..4835c75 100644
--- a/backend/services/youtube/youtubeVideos.ts
+++ b/backend/services/youtube/youtubeVideos.ts
@@ -1,5 +1,6 @@
import { ytFetch, optionalCount } from './youtubeApi.ts';
-import type { YouTubeApiError, YouTubeApiListResponse, YouTubeApiParams, YouTubeApiPlaylistItem, YouTubeApiVideo } from './youtubeApi.ts';
+import { UpstreamError } from '../../lib/errors.ts';
+import type { YouTubeApiListResponse, YouTubeApiParams, YouTubeApiPlaylistItem, YouTubeApiVideo } from './youtubeApi.ts';
import type { YouTubeVideo } from '../../../shared/types/youtube.ts';
export function normalizeYouTubeVideo(video: YouTubeApiVideo): YouTubeVideo {
@@ -36,38 +37,38 @@ export function normalizeYouTubeVideo(video: YouTubeApiVideo): YouTubeVideo {
}
async function fetchPlaylistPage(
- playlistId: string, pageToken: string, apiKey: string,
+ playlistId: string, pageToken: string, apiKey: string, signal?: AbortSignal,
): Promise<YouTubeApiListResponse<YouTubeApiPlaylistItem> | null> {
const params: YouTubeApiParams = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };
if (pageToken) params.pageToken = pageToken;
try {
- return await ytFetch<YouTubeApiListResponse<YouTubeApiPlaylistItem>>('playlistItems', params, apiKey);
+ return await ytFetch<YouTubeApiListResponse<YouTubeApiPlaylistItem>>('playlistItems', params, apiKey, signal);
} catch (err) {
// youtube reports the uploads playlist missing until the first public video
- if ((err as YouTubeApiError).reason === 'playlistNotFound') return null;
+ if (err instanceof UpstreamError && err.reason === 'playlistNotFound') return null;
throw err;
}
}
-async function fetchVideoDetails(playlistItems: YouTubeApiPlaylistItem[], apiKey: string): Promise<YouTubeVideo[]> {
+async function fetchVideoDetails(playlistItems: YouTubeApiPlaylistItem[], apiKey: string, signal?: AbortSignal): Promise<YouTubeVideo[]> {
const videoIds = playlistItems.map(item => item.snippet.resourceId.videoId).join(',');
const statsData = await ytFetch<YouTubeApiListResponse<YouTubeApiVideo>>('videos', {
part: 'statistics,contentDetails,snippet,status',
id: videoIds,
- }, apiKey);
+ }, apiKey, signal);
return statsData.items ? statsData.items.map(normalizeYouTubeVideo) : [];
}
-export async function fetchAllVideos(playlistId: string, apiKey: string, maxPages = 10): Promise<YouTubeVideo[]> {
+export async function fetchAllVideos(playlistId: string, apiKey: string, maxPages = 10, signal?: AbortSignal): Promise<YouTubeVideo[]> {
const allVideos: YouTubeVideo[] = [];
let pageToken = '';
let page = 0;
while (page < maxPages) {
- const data = await fetchPlaylistPage(playlistId, pageToken, apiKey);
+ const data = await fetchPlaylistPage(playlistId, pageToken, apiKey, signal);
if (!data || !data.items || data.items.length === 0) break;
- allVideos.push(...await fetchVideoDetails(data.items, apiKey));
+ allVideos.push(...await fetchVideoDetails(data.items, apiKey, signal));
pageToken = data.nextPageToken || '';
if (!pageToken) break;
diff --git a/backend/tests/fixtures/instagramApi.network.golden.json b/backend/tests/fixtures/instagramApi.network.golden.json
index e498f9a..23b56e3 100644
--- a/backend/tests/fixtures/instagramApi.network.golden.json
+++ b/backend/tests/fixtures/instagramApi.network.golden.json
@@ -14,7 +14,7 @@
}
},
{
- "error": "Instagram API request timed out"
+ "error": "Instagram took too long to answer. Try again in a moment."
},
{
"error": "Instagram API unreachable (read ECONNRESET)"
diff --git a/backend/tests/services/youtube/youtubeChannels.test.ts b/backend/tests/services/youtube/youtubeChannels.test.ts
index 9f1d5cf..8241338 100644
--- a/backend/tests/services/youtube/youtubeChannels.test.ts
+++ b/backend/tests/services/youtube/youtubeChannels.test.ts
@@ -3,7 +3,7 @@ import { resolveChannelId, fetchChannelData } from '../../../services/youtube/yo
import { assertGolden } from '../../fixtures/golden.ts';
import { installFetch, reply } from '../../fixtures/fakeFetch.ts';
import type { FetchMock } from '../../fixtures/fakeFetch.ts';
-import type { YouTubeApiError } from '../../../services/youtube/youtubeApi.ts';
+import type { UpstreamError } from '../../../lib/errors.ts';
let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
@@ -12,7 +12,7 @@ async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: (err as YouTubeApiError).message, reason: (err as YouTubeApiError).reason, status: (err as YouTubeApiError).status };
+ return { error: (err as UpstreamError).message, reason: (err as UpstreamError).reason, status: (err as UpstreamError).upstreamStatus };
}
}
diff --git a/backend/tests/services/youtube/youtubeVideos.test.ts b/backend/tests/services/youtube/youtubeVideos.test.ts
index 7e72bd8..f358548 100644
--- a/backend/tests/services/youtube/youtubeVideos.test.ts
+++ b/backend/tests/services/youtube/youtubeVideos.test.ts
@@ -4,7 +4,7 @@ import { assertGolden } from '../../fixtures/golden.ts';
import { installFetch, reply } from '../../fixtures/fakeFetch.ts';
import type { FetchMock, FakeReply } from '../../fixtures/fakeFetch.ts';
import { rawPlaylistItem, rawVideos } from '../../fixtures/youtubeFixtures.ts';
-import type { YouTubeApiError } from '../../../services/youtube/youtubeApi.ts';
+import type { UpstreamError } from '../../../lib/errors.ts';
let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
@@ -13,7 +13,7 @@ async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: (err as YouTubeApiError).message, reason: (err as YouTubeApiError).reason, status: (err as YouTubeApiError).status };
+ return { error: (err as UpstreamError).message, reason: (err as UpstreamError).reason, status: (err as UpstreamError).upstreamStatus };
}
}