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

Profile socials link #114

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
16 changes: 16 additions & 0 deletions src/app/api/socials/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import SocialsLink from "@/server/controllers/socials-controller";

export async function POST(request: Request) {
const body = await request.json();
const { userId, twitchUrl } = body;
try {
await SocialsLink({ userId, twitchUrl });
return Response.json({ message: "Social added successfully" }, { status: 200 });
} catch (error) {
console.error("Error adding socials:", error);
return Response.json(
{ error: "Error adding socials" },
{ status: 500 }
);
}
}
32 changes: 32 additions & 0 deletions src/app/api/twitch/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import twitchLive from "@/server/controllers/twitch-live";

export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const userId = searchParams.get('userId') || "";


try {
const res = await twitchLive({ userId });
const userName = res.twitchUrl.split('/').pop();
const clientId = process.env.TWITCH_CLIENT_ID;
const accessToken = process.env.TWITCH_ACCESS_TOKEN;

if (!clientId || !accessToken) {
throw new Error("Twitch credentials are not defined");
}

const liveStreamData = await fetch(`https://api.twitch.tv/helix/streams?user_login=${userName}`, {
headers: {
"Client-ID": clientId,
"Authorization": `Bearer ${accessToken}`
}
});

const data = await liveStreamData.json();
const isLive = data.data.length > 0;
return Response.json({ isLive });
} catch (err) {
console.error("Error in GET function:", err);
return Response.json({ Message: "Failed to fetch Twitch data." }, { status: 500 });
}
}
5 changes: 5 additions & 0 deletions src/app/socials/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Socials from "@/components/socials";

export default function SocialsPage() {
return <Socials/>
}
6 changes: 5 additions & 1 deletion src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export const {
}),
]
: []),
],
],callbacks: {
async session({session}) {
return session
}
}
};
});
3 changes: 1 addition & 2 deletions src/components/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ export function DataTable<TData, TValue>({
});

const handleRowClick = (row: any) => {
const route = `/profile/${row.original.profile_id}`;
router.push(route);
console.log(data)
};

return (
Expand Down
18 changes: 18 additions & 0 deletions src/components/leaderboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,21 @@ export default function Leaderboard() {

const { limit, onPaginationChange, skip, pagination } = usePagination();

const getLiveStatus = async (userId:string) => {
try {
const abc = "66e2cc127feec120c8fa955f"
const response = await fetch(`/api/twitch?userId=${abc}`);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const { isLive } = await response.json();
return isLive;
} catch (error) {
console.error(`Failed to fetch live status for userId ${userId}:`, error);
return false; // Default to false if there's an error
}
};

const getLeaderboardData = useCallback(
async (searchQuery: string) => {
try {
Expand All @@ -63,6 +78,9 @@ export default function Leaderboard() {
}

const { leaderboardPlayers, totalRecords } = await response.json();



setLeaderboardData(leaderboardPlayers);
setTotalRecords(totalRecords);
} catch (error) {
Expand Down
51 changes: 51 additions & 0 deletions src/components/socials.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"use client";
import { Twitch } from "lucide-react";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { toast } from "./ui/use-toast";

export default function Socials() {
const [twitchUrl, setTwitchUrl] = useState("");
const { data: session } = useSession();
const loggedInUserId = session?.userId;
async function handleSubmit(e:React.FormEvent<HTMLFormElement>):Promise<void> {
e.preventDefault();
const response = await fetch("/api/socials", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId: loggedInUserId, twitchUrl }),
});

if (response.ok) {
const data = await response.json();
toast({
title: data.message || "Twitch URL added successfully",
duration: 3000,
});
} else {
const errorData = await response.json();
toast({
title: errorData.error || "Error adding Twitch URL",
duration: 3000,
});
}
}
return (
<div className="flex items-center justify-center min-h-screen">
<div className="flex items-center">
<Twitch className="w-10 h-10 text-purple-500 transition-transform duration-300 ease-in-out transform hover:scale-110 hover:text-purple-700" />
<form className="flex items-center ml-2" onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter your twitch channel url"
className="border rounded-l-md px-2 py-1 w-[250px]"
onChange={(e)=>{setTwitchUrl(e.target.value)}}
/>
<button className="bg-purple-500 text-white rounded-r-md px-3 py-1 hover:bg-purple-700 transition ml-4">
Submit
</button>
</form>
</div>
</div>
);
}
5 changes: 5 additions & 0 deletions src/db/mongo/model/SocialsModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import mongoose, { model } from "mongoose";
import { SocialsSchema } from "../schemas/SocialsSchema";
import { Socials } from "@/types/Socials";

export const SocialsModel = mongoose.models.Socials || model<Socials>("Socials", SocialsSchema);
1 change: 1 addition & 0 deletions src/db/mongo/schemas/LeaderboardPlayerSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ export const LeaderboardPlayerSchema = new Schema({
country: { type: String, required: true },
winPercent: { type: Number, required: true },
totalGames: { type: Number, required: true },
isLive: { type: Boolean, required: true },
});
8 changes: 8 additions & 0 deletions src/db/mongo/schemas/SocialsSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Schema } from "mongoose";

export const SocialsSchema = new Schema({
userId: { type: String, required: true },
twitchUrl: { type: String, default: null },
}, {
timestamps: true,
});
17 changes: 17 additions & 0 deletions src/server/controllers/socials-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { SocialsModel } from "@/db/mongo/model/SocialsModel";
import getMongoClient from "@/db/mongo/mongo-client";
import { Socials } from "@/types/Socials";

export default async function SocialsLink(params:Socials): Promise<void> {
const { userId, twitchUrl } = params;
await getMongoClient();
try {
const result = await SocialsModel.create({ userId, twitchUrl });
if (result.matchedCount === 0) {
throw new Error(`Error creating social`);
}
} catch (error) {
console.error("Error editing game title:", error);
throw error;
}
}
18 changes: 18 additions & 0 deletions src/server/controllers/twitch-live.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { SocialsModel } from "@/db/mongo/model/SocialsModel";
import getMongoClient from "@/db/mongo/mongo-client";

type Params = {
userId: string;
};

export default async function twitchLive(params: Params): Promise<any> {
const { userId } = params;
await getMongoClient();
try {
const twitchName = await SocialsModel.findOne({ userId });
return twitchName;
} catch (err) {
console.error("Error fetching Twitch name:", err);
throw new Error("Failed to fetch Twitch name.");
}
}
1 change: 1 addition & 0 deletions src/types/LeaderboardPlayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ export interface ILeaderboardPlayer {
country: String;
winPercent: Number;
totalGames: Number;
isLive: Boolean;
}
4 changes: 4 additions & 0 deletions src/types/Socials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type Socials = {
userId: string;
twitchUrl: string;
};