@@ -5,6 +5,7 @@ export async function fetchFromSupabase(
55 endpoint : string ,
66 options : RequestInit
77) {
8+ console . log ( "options" , options ) ;
89 const response = await fetch ( `${ SUPABASE_URL } /rest/v1/${ endpoint } ` , {
910 ...options ,
1011 headers : {
@@ -13,16 +14,67 @@ export async function fetchFromSupabase(
1314 Authorization : `Bearer ${ SUPABASE_KEY } ` ,
1415 } ,
1516 } ) ;
16- return await response . json ( ) ;
17- }
1817
19- export function generateShortUrl ( ) : string {
18+ if ( ! response . ok ) {
19+ throw new Error ( `Supabase request failed: ${ response . statusText } ` ) ;
20+ }
21+ let jsonResponse = await response . json ( ) ;
22+ console . log ( "jsonResponse" , jsonResponse ) ;
23+ return jsonResponse ;
24+ }
25+ import {
26+ fetchFromSupabase ,
27+ generateShortUrl as generateUuidShort ,
28+ } from "./utils.ts" ;
29+ export async function generateShortUrl ( longUrl : string ) : Promise < string > {
30+ try {
31+ let { data, error } = await fetchFromSupabase (
32+ "urls?select=short_url&long_url=eq." + longUrl ,
33+ { method : "GET" }
34+ ) ;
35+ if ( error ) {
36+ console . error ( "Error checking for existing long URL:" , error ) ;
37+ throw error ;
38+ }
39+ if ( data && data [ 0 ] ?. short_url ) {
40+ return data [ 0 ] . short_url ;
41+ }
42+ let shortUrl : string ;
43+ let isCollision = true ;
44+ while ( isCollision ) {
45+ shortUrl = generateUuidShort ( ) ;
46+ ( { data, error } = await fetchFromSupabase (
47+ "urls?select=short_url&short_url=eq." + shortUrl ,
48+ { method : "GET" }
49+ ) ) ;
50+ if ( error ) {
51+ console . error ( "Error checking for collision:" , error ) ;
52+ throw error ;
53+ }
54+ isCollision = data . length > 0 ;
55+ }
56+ ( { data, error } = await fetchFromSupabase ( "urls" , {
57+ method : "POST" ,
58+ headers : { "Content-Type" : "application/json" } ,
59+ body : JSON . stringify ( { short_url : shortUrl , long_url : longUrl } ) ,
60+ } ) ) ;
61+ if ( error ) {
62+ console . error ( "Error inserting new URL:" , error ) ;
63+ throw error ;
64+ }
65+ return shortUrl ;
66+ } catch ( err ) {
67+ console . error ( "Error in generateShortUrl function:" , err ) ;
68+ throw err ;
69+ }
70+ }
71+ export function generateUuidShort ( ) : string {
2072 return crypto . randomUUID ( ) . substring ( 0 , 7 ) ;
2173}
22-
2374export default function handler ( ) {
2475 return {
2576 fetchFromSupabase,
2677 generateShortUrl,
78+ generateShortUrl,
2779 } ;
2880}
0 commit comments