Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app/actions/get-admin-users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,21 @@ export async function getAdminUsersDetails() {
}

// 🚀 OMIJA Zabezpieczenia RLS do sczytania cudzych kuponów z bazy
export async function getAdminUserCoupons(userId: string) {
export async function getAdminUserCoupons(userId: string | string[]) {
const adminKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
if (!adminKey || !url) {
return { success: false, coupons: [], error: 'Brak kluczy do bazy.' };
}

const supabaseAdmin = createClient(url, adminKey);
const userIds = Array.isArray(userId) ? userId : [userId];

try {
const { data: coupons, error } = await supabaseAdmin
.from('kupony')
.select('*')
.eq('user_id', userId)
.in('user_id', userIds)
.order('created_at', { ascending: false });

if (error) throw error;
Expand Down
36 changes: 36 additions & 0 deletions benchmark.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { performance } from 'perf_hooks';

// Simulate the old N+1 behavior vs the new batched behavior
async function mockOldQuery(userId: string) {
// simulate DB latency
await new Promise(resolve => setTimeout(resolve, 50));
return [{ id: Math.random(), user_id: userId }];
}

async function mockNewQuery(userIds: string[]) {
// simulate DB latency
await new Promise(resolve => setTimeout(resolve, 50));
return userIds.map(userId => ({ id: Math.random(), user_id: userId }));
}

async function runBenchmark() {
console.log('Running benchmark for 10 users...');
const userIds = Array.from({ length: 10 }, (_, i) => `user_${i}`);

// Old behavior: N queries
const startOld = performance.now();
for (const id of userIds) {
await mockOldQuery(id);
}
const endOld = performance.now();
console.log(`Baseline (N+1 queries): ${(endOld - startOld).toFixed(2)} ms`);

// New behavior: 1 batched query
const startNew = performance.now();
await mockNewQuery(userIds);
const endNew = performance.now();
console.log(`Optimized (1 batched query): ${(endNew - startNew).toFixed(2)} ms`);
console.log(`Improvement: ${(((endOld - startOld) - (endNew - startNew)) / (endOld - startOld) * 100).toFixed(2)}% faster`);
}

runBenchmark();