Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supabase and leetcode api #30

Merged
merged 7 commits into from
Jan 8, 2025
Merged
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
93 changes: 93 additions & 0 deletions app/api/leetcode/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { supabase } from '@/lib/supabaseClient';
import axios from 'axios';
import { NextRequest, NextResponse } from 'next/server';

// Fetch LeetCode stats
const fetchLeetCodeStats = async (username: string) => {
const query = `
query getUserProfile($username: String!) {
matchedUser(username: $username) {
username
profile {
realName
ranking
}
submitStats {
acSubmissionNum {
difficulty
count
}
}
}
}
`;
try {
const variables = { username };
const { data } = await axios.post('https://leetcode.com/graphql', {
query,
variables,
});
return data.data.matchedUser;
} catch (error) {
console.error('Error fetching LeetCode data:', error);
return null;
}
};

// Store transformed user stats in Supabase
const storeUserStats = async (id: string, stats: any) => {
const entry = {
id: String(id),
ranking: stats.profile.ranking,
solved_easy: stats.submitStats.acSubmissionNum.find((item: any) => item.difficulty === 'Easy')?.count || "0",
solved_medium: stats.submitStats.acSubmissionNum.find((item: any) => item.difficulty === 'Medium')?.count || "0",
solved_hard: stats.submitStats.acSubmissionNum.find((item: any) => item.difficulty === 'Hard')?.count || "0",
};
const { data, error } = await supabase.from('user_info').upsert([entry]);

if (error) {
console.error('Error storing data in Supabase:', error);
}

return data;
};

// Transform LeetCode data into a UI-friendly structure
const transformLeetCodeData = (stats: any) => {
return {
username: stats.username,
profile: {
realName: stats.profile.realName || "Unknown",
ranking: stats.profile.ranking?.toString() || "0",
},
submitStats: {
acSubmissionNum: stats.submitStats.acSubmissionNum.map((item: any) => ({
difficulty: item.difficulty,
count: item.count?.toString() || "0",
})),
},
};
};

// API POST Handler
export async function POST(req: NextRequest) {
const searchParams = req.nextUrl.searchParams;
const username = searchParams.get('username');
const id = searchParams.get('id');

if (!username || !id) {
return NextResponse.json({ error: "Username and id are required" }, { status: 400 });
}

const stats = await fetchLeetCodeStats(username);

if (!stats) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}

const transformedStats = transformLeetCodeData(stats);

await storeUserStats(id, transformedStats);

return NextResponse.json({ message: "Success", stats: transformedStats });
}
78 changes: 78 additions & 0 deletions app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"use client"
import { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabaseClient';
import { useRouter } from 'next/navigation';
import Navbar from '@/components/header';
import StatsCard from '@/components/Stats';
import { fetchLeetCodeStats } from '@/lib/utils';

export default function Dashboard() {
const [userData, setUserData] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const router = useRouter();

useEffect(() => {
const fetchData = async () => {
try {
const { data, error } = await supabase.auth.getSession();

if (error) throw new Error("Error fetching session.");

const session = data.session;
if (!session) {
router.push('/login');
return;
}
// Fetch user-specific data in a single call
const { data: userInfo, error: userInfoError } = await supabase
.from('user_info')
.select('*')
.eq('user_id', session.user.id)
.single();

if (userInfoError) throw userInfoError;

setUserData(userInfo);

} catch (err: any) {
console.error(err);
setError(err.message || 'An error occurred.');
router.push('/login');
} finally {
setLoading(false);
}
};

fetchData();
}, [router]);

if (loading) return <p>Loading...</p>;

if (error) {
return (
<div>
<Navbar userId={userData.user_id} />
<p className="text-red-500">{error}</p>
</div>
);
}

return (
<div>
<Navbar userId={userData?.user_id} />
<div className="container mx-auto p-4">
<h1 className="text-xl font-bold mb-4">Welcome, {userData.name}</h1>
<div className="mb-4">
<p>LeetCode Username: {userData.leetcode_username}</p>
<p>Gender: {userData.gender}</p>
</div>

<div className="mt-6">
<h2 className="text-lg font-bold mb-2">LeetCode Stats</h2>
<StatsCard leetcodeUsername={userData.leetcode_username} id={userData.id} />
</div>
</div>
</div>
);
}
9 changes: 9 additions & 0 deletions app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import LoginForm from "@/components/LoginForm";

export default function SignupPage() {
return (
<div className="">
<LoginForm />
</div>
);
}
9 changes: 9 additions & 0 deletions app/signup/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import SignupForm from "@/components/SignupForm";

export default function SignupPage() {
return (
<div className="">
<SignupForm />
</div>
);
}
110 changes: 110 additions & 0 deletions components/LoginForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
'use client';

import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useRouter } from 'next/navigation';
import { supabase } from '@/lib/supabaseClient';
import Link from 'next/link';

const LoginForm: React.FC = () => {
const router = useRouter();
const [formData, setFormData] = useState<{ email: string; password: string }>({
email: '',
password: '',
});

const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);

const { email, password } = formData;

try {
// Attempt user login
const { data, error: loginError } = await supabase.auth.signInWithPassword({ email, password });

if (loginError) {
throw new Error(loginError.message);
}

// Redirect to dashboard if login succeeds
if (data.session) {
router.push('/dashboard');
} else {
throw new Error('Unable to retrieve session after login.');
}
} catch (err: any) {
console.error('Login Error:', err);
setError(err.message || 'Something went wrong.');
} finally {
setLoading(false);
}
};

return (
<main className="w-full h-screen flex flex-col items-center justify-center px-4">
<div className="max-w-sm w-full text-gray-600">
<div className="p-6 rounded-lg shadow-lg ">
<h2 className="text-2xl font-bold mb-4">Log In</h2>
<form onSubmit={handleSubmit}>
{/* Email Field */}
<div className="mb-4">
<Label htmlFor="email">Email</Label>
<Input
id="email"
name="email"
type="email"
placeholder="[email protected]"
value={formData.email}
onChange={handleChange}
required
/>
</div>

{/* Password Field */}
<div className="mb-4">
<Label htmlFor="password">Password</Label>
<Input
id="password"
name="password"
type="password"
placeholder="********"
value={formData.password}
onChange={handleChange}
required
/>
</div>

{/* Error Message */}
{error && <p className="text-red-500 mb-4">{error}</p>}

{/* Submit Button */}
<Button type="submit" disabled={loading} className="w-full">
{loading ? 'Logging in...' : 'Log In'}
</Button>

<div className="flex justify-center mt-4">
<Link href="/signup" className="text-sm text-gray-500">
Don't have an account?
<span className='hover:underline ms-1'>Sign up</span>
</Link>
</div>
</form>
</div>
</div>
</main>
);
};

export default LoginForm;
Loading
Loading