hermes-web/app/api/settings/connections/twitch/route.ts

85 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-12-30 05:56:40 -05:00
import axios from "axios"
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserUsingAPI from "@/lib/validate-api";
export async function GET(req: Request) {
try {
const user = await fetchUserUsingAPI(req)
if (!user) {
console.log("TWITCH CONNECT", user)
return new NextResponse("Unauthorized", { status: 401 });
}
const { searchParams } = new URL(req.url)
let userId = searchParams.get('id')
if (userId == null) {
if (user != null) {
userId = user.id as string;
}
}
const connection = await db.twitchConnection.findFirst({
where: {
userId: userId as string
}
});
return NextResponse.json(connection);
} catch (error) {
console.log("[CONNECTION/TWITCH]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function POST(req: Request) {
try {
const { id, secret } = await req.json();
const user = await fetchUserUsingAPI(req)
console.log("userrr:", user)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
console.log(id, secret)
let response = null;
try {
response = await axios.post("https://id.twitch.tv/oauth2/token", {
client_id: id,
client_secret: secret,
grant_type: "client_credentials"
});
console.log(response.data)
} catch (error) {
console.log("[CONNECTIONS/TWITCH/TOKEN]", error);
return;
}
console.log(user.username)
let info = await axios.get("https://api.twitch.tv/helix/users?login=" + user.username, {
headers: {
"Authorization": "Bearer " + response.data['access_token'],
"Client-Id": id
}
})
console.log(info.data.data)
const broadcasterId = info.data.data[0]['id']
const username = info.data.data[0]['login']
const connection = await db.twitchConnection.create({
data: {
id,
secret,
userId: user.id as string,
broadcasterId,
username
}
});
return NextResponse.json(connection);
} catch (error) {
console.log("[CONNECTION/TWITCH]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}