From 3dba56cb45bc71ce7e18b0c81c3b53a9415c084b Mon Sep 17 00:00:00 2001 From: Rushil Perera Date: Sat, 21 Sep 2024 14:02:07 -0400 Subject: [PATCH] feat: return user info when authenticating --- .../anilist/{getUsername.ts => getUser.ts} | 22 ++++++++++++++----- src/controllers/auth/anilist/index.ts | 16 +++++++++----- 2 files changed, 28 insertions(+), 10 deletions(-) rename src/controllers/auth/anilist/{getUsername.ts => getUser.ts} (53%) diff --git a/src/controllers/auth/anilist/getUsername.ts b/src/controllers/auth/anilist/getUser.ts similarity index 53% rename from src/controllers/auth/anilist/getUsername.ts rename to src/controllers/auth/anilist/getUser.ts index ff2c0c5..3aee298 100644 --- a/src/controllers/auth/anilist/getUsername.ts +++ b/src/controllers/auth/anilist/getUser.ts @@ -1,22 +1,34 @@ import { graphql } from "gql.tada"; import { GraphQLClient } from "graphql-request"; -const GetUsernameQuery = graphql(` - query GetUsername { +const GetUserQuery = graphql(` + query GetUser { Viewer { name + avatar { + medium + large + } + statistics { + anime { + minutesWatched + episodesWatched + count + meanScore + } + } } } `); -export function getUsername(aniListToken: string) { +export function getUser(aniListToken: string) { const client = new GraphQLClient("https://graphql.anilist.co/"); return client - .request(GetUsernameQuery, undefined, { + .request(GetUserQuery, undefined, { Authorization: `Bearer ${aniListToken}`, }) - .then((data) => data?.Viewer?.name) + .then((data) => data?.Viewer) .catch((err) => { if (err.response?.status === 401 || err.response?.status === 429) { return null; diff --git a/src/controllers/auth/anilist/index.ts b/src/controllers/auth/anilist/index.ts index e380838..2c19382 100644 --- a/src/controllers/auth/anilist/index.ts +++ b/src/controllers/auth/anilist/index.ts @@ -12,7 +12,7 @@ import { EpisodesResponseSchema } from "~/types/episode"; import { ErrorResponse, ErrorResponseSchema } from "~/types/schema"; import { Title } from "~/types/title"; -import { getUsername } from "./getUsername"; +import { getUser } from "./getUser"; import { getWatchingTitles } from "./getWatchingTitles"; const route = createRoute({ @@ -69,22 +69,28 @@ app.openapi(route, async (c) => { } try { - const username = await getUsername(aniListToken); - if (!username) { + const user = await getUser(aniListToken); + if (!user) { return c.json(ErrorResponse, { status: 401 }); } - await associateDeviceIdWithUsername(env(c, "workerd"), deviceId, username); + await associateDeviceIdWithUsername( + env(c, "workerd"), + deviceId!, + user.name, + ); return streamSSE( c, async (stream) => { + stream.writeSSE({ event: "user", data: JSON.stringify(user) }); + let currentPage = 1; let hasNextPage = true; do { const { mediaList, pageInfo } = await getWatchingTitles( - username, + user.name, currentPage++, c.executionCtx, );