All files / src/common/api optimizedNewsletterApi.ts

84.86% Statements 185/218
77.77% Branches 42/54
57.14% Functions 12/21
84.86% Lines 185/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312                  1x 1x               1x     1x     11x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     1x 1x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x   11x 1x 1x 1x 1x 1x 1x 1x 1x     11x     11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x     1x 2x 2x   2x 2x 1x         1x   2x 2x 2x 2x 2x 2x   2x             2x 2x 2x     1x   1x 1x 1x   1x   1x 1x 1x   1x   1x 1x 1x   1x 1x 1x   1x 1x 1x   1x   1x 1x 1x   1x           1x           1x           1x           1x   1x 1x 1x   1x 1x 1x 1x   1x 1x   1x 1x 1x 1x   1x 1x   1x 1x 1x 1x   1x 1x   1x                       1x           1x           1x           1x         1x  
import { NewsletterWithRelations, Tag } from '../types';
import {
  BatchResult,
  BulkUpdateNewsletterParams,
  CreateNewsletterParams,
  NewsletterQueryParams,
  PaginatedResponse,
  UpdateNewsletterParams,
} from '../types/api';
import { logger } from '../utils/logger';
import {
  handleSupabaseError,
  requireAuth,
  supabase,
  withPerformanceLogging,
} from './supabaseClient';
 
// Initialize logger
const log = logger;
 
// Transform the optimized response to match existing NewsletterWithRelations interface
const transformOptimizedResponse = (data: any): NewsletterWithRelations => {
  // The optimized function returns data in the same format as the original
  // but with pre-joined source and tags as JSON
  const { source, tags, ...newsletterData } = data;
 
  // Transform source if it exists
  let transformedSource = null;
  if (source && typeof source === 'object') {
    transformedSource = {
      id: source.id,
      name: source.name || 'Unknown',
      from: source.from || null,
      created_at: source.created_at || new Date().toISOString(),
      updated_at: source.updated_at || new Date().toISOString(),
      user_id: source.user_id || null,
    };
  }
 
  // Transform tags if they exist
  let transformedTags: Tag[] = [];
  if (tags && Array.isArray(tags)) {
    transformedTags = tags.map((tag: any) => ({
      id: tag.id,
      name: tag.name,
      color: tag.color,
      user_id: tag.user_id,
      created_at: tag.created_at,
      newsletter_count: tag.newsletter_count,
    }));
  }
 
  return {
    ...newsletterData,
    source: transformedSource,
    tags: transformedTags,
    is_archived: Boolean(newsletterData.is_archived),
    newsletter_source_id: newsletterData.newsletter_source_id,
    // Ensure all required properties
    id: newsletterData.id as string,
    title: newsletterData.title as string,
    content: newsletterData.content as string,
    summary: newsletterData.summary as string,
    image_url: newsletterData.image_url as string,
    received_at: newsletterData.received_at as string,
    updated_at: newsletterData.updated_at as string,
    is_read: Boolean(newsletterData.is_read),
    is_liked: Boolean(newsletterData.is_liked),
    user_id: newsletterData.user_id as string,
    word_count: Number(newsletterData.word_count) || 0,
    estimated_read_time: Number(newsletterData.estimated_read_time) || 0,
  };
};
 
// Optimized Newsletter API Service using the new database functions
export const optimizedNewsletterApi = {
  async getAll(
    params: NewsletterQueryParams = {}
  ): Promise<PaginatedResponse<NewsletterWithRelations>> {
    return withPerformanceLogging('optimizedNewsletters.getAll', async () => {
      const user = await requireAuth();
 
      log.debug('Using optimized newsletter query', {
        component: 'OptimizedNewsletterApi',
        action: 'get_all_optimized',
        metadata: {
          ...params,
          userId: user.id,
        },
      });
 
      // Map the parameters to the optimized function parameters
      const rpcParams = {
        p_user_id: user.id,
        p_tag_ids: params.tagIds && params.tagIds.length > 0 ? params.tagIds : null,
        p_is_read: params.isRead ?? null,
        p_is_archived: params.isArchived ?? null,
        p_is_liked: params.isLiked ?? null,
        p_source_ids: params.sourceIds && params.sourceIds.length > 0 ? params.sourceIds : null,
        p_date_from: params.dateFrom || null,
        p_date_to: params.dateTo || null,
        p_search: params.search || null,
        p_limit: params.limit || 50,
        p_offset: params.offset || 0,
        p_order_by: params.orderBy || 'received_at',
        p_order_direction: params.ascending ? 'ASC' : 'DESC',
      };
 
      // Call the optimized function
      const { data, error } = await supabase.rpc('get_newsletters', rpcParams);
 
      if (error) {
        log.error('Optimized newsletter query failed', {
          component: 'OptimizedNewsletterApi',
          action: 'get_all_error',
          metadata: { userId: user.id, params: rpcParams, error },
        });
        handleSupabaseError(error);
        throw error;
      }
 
      // Transform the data
      const transformedData = data ? data.map(transformOptimizedResponse) : [];
 
      // Extract count from result if available (it's in every row), otherwise use data length
      const totalCount = data && data.length > 0 ? Number(data[0].total_count) : 0;
      const limit = params.limit || 50;
      const offset = params.offset || 0;
      const page = Math.floor(offset / limit) + 1;
      const hasMore = totalCount ? offset + limit < totalCount : false;
 
      const result = {
        data: transformedData,
        count: totalCount,
        page,
        limit,
        hasMore,
        nextPage: hasMore ? page + 1 : null,
        prevPage: page > 1 ? page - 1 : null,
      };
 
      log.debug('Optimized newsletter query completed', {
        component: 'OptimizedNewsletterApi',
        action: 'get_all_success',
        metadata: {
          dataCount: transformedData.length,
          totalCount,
          page,
          hasMore,
        },
      });
 
      return result;
    });
  },
 
  // Get newsletter by ID - still use the original method for single items
  async getById(id: string, includeRelations = true): Promise<NewsletterWithRelations | null> {
    return withPerformanceLogging('optimizedNewsletters.getById', async () => {
      const user = await requireAuth();
 
      let selectClause = '*';
      if (includeRelations) {
        selectClause = `
          *,
          source:newsletter_sources(*),
          tags:newsletter_tags(tag:tags(*))
        `;
      }
 
      const { data, error } = await supabase
        .from('newsletters')
        .select(selectClause)
        .eq('id', id)
        .eq('user_id', user.id)
        .single();
 
      if (error) {
        if (error.code === 'PGRST116') {
          return null; // Not found
        }
        handleSupabaseError(error);
      }
 
      return data ? transformOptimizedResponse(data as any) : null;
    });
  },
 
  // Other methods remain the same as they don't benefit from the optimization
  async create(params: CreateNewsletterParams): Promise<NewsletterWithRelations> {
    // Delegate to original API for create operations
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.create(params);
  },
 
  async update(params: UpdateNewsletterParams): Promise<NewsletterWithRelations> {
    // Delegate to original API for update operations
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.update(params);
  },
 
  async delete(id: string): Promise<boolean> {
    // Delegate to original API for delete operations
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.delete(id);
  },
 
  async bulkUpdate(
    params: BulkUpdateNewsletterParams
  ): Promise<BatchResult<NewsletterWithRelations>> {
    // Delegate to original API for bulk operations
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.bulkUpdate(params);
  },
 
  async markAsRead(id: string): Promise<NewsletterWithRelations> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.markAsRead(id);
  },
 
  async markAsUnread(id: string): Promise<NewsletterWithRelations> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.markAsUnread(id);
  },
 
  async toggleArchive(id: string): Promise<NewsletterWithRelations> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.toggleArchive(id);
  },
 
  async bulkArchive(ids: string[]): Promise<BatchResult<NewsletterWithRelations>> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.bulkArchive(ids);
  },
 
  async bulkUnarchive(ids: string[]): Promise<BatchResult<NewsletterWithRelations>> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.bulkUnarchive(ids);
  },
 
  async toggleLike(id: string): Promise<NewsletterWithRelations> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.toggleLike(id);
  },
 
  async getByTags(
    tagIds: string[],
    params: Omit<NewsletterQueryParams, 'tagIds'> = {}
  ): Promise<PaginatedResponse<NewsletterWithRelations>> {
    // Use optimized API for tag filtering
    return this.getAll({ ...params, tagIds });
  },
 
  async getBySource(
    sourceId: string,
    params: Omit<NewsletterQueryParams, 'sourceIds'> = {}
  ): Promise<PaginatedResponse<NewsletterWithRelations>> {
    // Use optimized API for source filtering
    return this.getAll({ ...params, sourceIds: [sourceId] });
  },
 
  async search(
    query: string,
    params: Omit<NewsletterQueryParams, 'search'> = {}
  ): Promise<PaginatedResponse<NewsletterWithRelations>> {
    // Use optimized API for search
    return this.getAll({ ...params, search: query });
  },
 
  async getStats(): Promise<{
    total: number;
    read: number;
    unread: number;
    archived: number;
    liked: number;
  }> {
    // Delegate to original API for stats
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.getStats();
  },
 
  async countBySource(): Promise<Record<string, number>> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.countBySource();
  },
 
  async getTotalCountBySource(): Promise<Record<string, number>> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.getTotalCountBySource();
  },
 
  async getUnreadCountBySource(): Promise<Record<string, number>> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.getUnreadCountBySource();
  },
 
  async getUnreadCount(sourceId?: string | null): Promise<number> {
    // Delegate to original API
    const { newsletterApi } = await import('./newsletterApi');
    return newsletterApi.getUnreadCount(sourceId);
  },
};