feat: return user info when authenticating

This commit is contained in:
2024-09-21 14:02:07 -04:00
parent 755ae4b94f
commit 3dba56cb45
2 changed files with 28 additions and 10 deletions

View File

@@ -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;

View File

@@ -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,
);