All files / app/api/profiles/check-username route.ts

100% Statements 41/41
91.66% Branches 11/12
100% Functions 1/1
100% Lines 41/41

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 521x       24x 24x 24x 24x   24x 2x 2x     22x 24x 6x 6x 6x 6x 6x 6x 6x 6x     16x 15x 15x 15x   24x 1x 1x 1x 1x 1x 1x   14x 14x 14x 14x 24x 24x 24x 24x 1x 1x 1x 24x  
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { checkUsernameSchema } from '@/lib/validations/profile';
 
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const username = searchParams.get('username');
 
    if (!username) {
      return NextResponse.json({ success: false, error: 'Username is required' }, { status: 400 });
    }
 
    // Validate format
    const validation = checkUsernameSchema.safeParse({ username: username.toLowerCase() });
    if (!validation.success) {
      return NextResponse.json({
        success: true,
        data: {
          available: false,
          reason: validation.error.issues[0]?.message || 'Invalid username format',
        },
      });
    }
 
    // Check availability using database function
    const supabase = await createClient();
    const { data, error } = await supabase.rpc('is_username_available', {
      username_to_check: username.toLowerCase(),
    });
 
    if (error) {
      console.error('[Username Check] Error:', error);
      return NextResponse.json(
        { success: false, error: 'Failed to check username availability' },
        { status: 500 }
      );
    }
 
    return NextResponse.json({
      success: true,
      data: {
        available: data === true,
        reason: data === true ? null : 'Username is already taken or reserved',
      },
    });
  } catch (error) {
    console.error('[Username Check] Error:', error);
    return NextResponse.json({ success: false, error: 'Internal server error' }, { status: 500 });
  }
}