refactor: improve the download count increment management

This commit is contained in:
Bharath Lakshman Kumar
2024-08-23 14:28:58 +05:30
parent 217e5d57b0
commit b3d5529080

View File

@@ -1,31 +1,49 @@
"use server"; "use server";
import { createClient } from '@supabase/supabase-js' import { createClient } from "@supabase/supabase-js";
import { releases } from "./releases";
const supabaseUrl = 'https://dmthyedfjzcysoekmyns.supabase.co' const supabaseUrl = "https://dmthyedfjzcysoekmyns.supabase.co";
const supabaseKey = process.env.SUPABASE_KEY as string; const supabaseKey = process.env.SUPABASE_KEY as string;
const supabase = createClient(supabaseUrl, supabaseKey); const supabase = createClient(supabaseUrl, supabaseKey);
export async function addDownload(platform: string) { const DOWNLOADS_TABLE = "downloads";
// Check if the download count for the platform exists const PLATFORM_COLUMN = "platform";
const COUNT_COLUMN = "count";
export async function incrementDownloadCount(platform: keyof typeof releases) {
try {
//? Check if the download count for the platform exists
const { data, error } = await supabase const { data, error } = await supabase
.from('downloads') .from(DOWNLOADS_TABLE)
.select('count') .select(COUNT_COLUMN)
.eq('platform', platform) .eq(PLATFORM_COLUMN, platform);
// If it doesn't exist, create it
console.log(data) if (error) throw new Error("Error fetching download count");
if (data?.length === 0 || data === null) {
const {data, error} = await supabase if (!data || data.length === 0) {
.from('downloads') //? If it doesn't exist, create it
.insert([{ platform, count: 1 }]); const { data: insertData, error: insertError } = await supabase
if (error) { .from(DOWNLOADS_TABLE)
console.error(error) .insert([{ platform, count: 1 }]);
}
if (insertError) throw new Error("Error inserting download count");
return insertData;
} else { } else {
// If it exists, increment the count //? If it exists, increment the count
await supabase const newCount = data![0][COUNT_COLUMN] + 1;
.from('downloads') const { data: updateData, error: updateError } = await supabase
.update({ count: data![0].count + 1 }) .from(DOWNLOADS_TABLE)
.eq('platform', platform) .update({ count: newCount })
.eq(PLATFORM_COLUMN, platform);
if (updateError) throw new Error("Error updating download count");
return updateData;
} }
} catch (err) {
console.error("Unexpected error in addDownload:", err);
throw err;
}
} }