From 590e7d8265a6f02e4096d8ba7c3875453885346e Mon Sep 17 00:00:00 2001 From: aronmal Date: Sun, 11 Feb 2024 23:22:13 +0100 Subject: [PATCH] Chore: Revert to 'use server' functions --- src/components/NavUser.tsx | 2 + src/routes/api/config/[guildId].tsx | 106 ------------------------ src/routes/api/config/index.tsx | 60 -------------- src/routes/config/[guildId].tsx | 120 ++++++++++++++++++++++++---- src/routes/config/index.tsx | 86 +++++++++++++++----- 5 files changed, 171 insertions(+), 203 deletions(-) delete mode 100644 src/routes/api/config/[guildId].tsx delete mode 100644 src/routes/api/config/index.tsx diff --git a/src/components/NavUser.tsx b/src/components/NavUser.tsx index 1fab326..7d27cc4 100644 --- a/src/components/NavUser.tsx +++ b/src/components/NavUser.tsx @@ -42,6 +42,8 @@ async function getUser() { .execute() )[0]; + console.log("userInfo", "success"); + return { success: true, message: "", ...user }; } diff --git a/src/routes/api/config/[guildId].tsx b/src/routes/api/config/[guildId].tsx deleted file mode 100644 index 48d25e1..0000000 --- a/src/routes/api/config/[guildId].tsx +++ /dev/null @@ -1,106 +0,0 @@ -import { getSession } from "@auth/solid-start"; -import { APIEvent } from "@solidjs/start/server/types"; -import { eq } from "drizzle-orm"; -import moment from "moment-timezone"; -import createClient from "openapi-fetch"; -import db from "~/drizzle"; -import { accounts } from "~/drizzle/schema"; -import { authOptions } from "~/server/auth"; -import { paths } from "~/types/discord"; - -type data = { - success: boolean | null; - guild: { - id: string; - name: string | undefined; - icon: string | null | undefined; - channel: string; - channels: { - id: string; - name: string; - }[]; - }; - tzNames: string[]; -}; - -export const GET = async ( - event: APIEvent, -): Promise< - { success: false; message: string } | (data & { success: true }) -> => { - const id = event.params.guildId; - if (!event) return { success: false, message: "No request event!" }; - - const session = await getSession(event.request, authOptions); - if (!session?.user?.id) - return { success: false, message: "No user with id!" }; - - const { DISCORD_ACCESS_TOKEN } = ( - await db - .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token }) - .from(accounts) - .where(eq(accounts.userId, session.user?.id)) - .limit(1) - .execute() - )[0]; - if (!DISCORD_ACCESS_TOKEN) - return { success: false, message: "No discord access token!" }; - - const { GET } = createClient({ - baseUrl: "https://discord.com/api/v10", - }); - const guildsRequest = await GET("/users/@me/guilds", { - headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` }, - }); - const channelsRequest = await GET("/guilds/{guild_id}/channels", { - params: { - path: { - guild_id: id, - }, - }, - headers: { Authorization: `Bot ${import.meta.env.VITE_DISCORD_BOT_TOKEN}` }, - }); - if (guildsRequest.error || channelsRequest.error) { - console.log(guildsRequest.error, channelsRequest.error, event.path); - return { - success: false, - message: "Error on one of the discord api requests!", - }; - } - - const guild = guildsRequest.data?.find((e) => e.id === id); - - if (!guild) - return { - success: false, - message: "User is in no such guild with requested id!", - }; - if (!(parseInt(guild.permissions) & (1 << 5))) - return { - success: false, - message: - "User is no MANAGE_GUILD permissions on this guild with requested id!", - }; - - let channels: data["guild"]["channels"] = []; - channelsRequest.data?.forEach((channel) => { - if (channel.type !== 0) return; - channels.push({ - id: channel.id, - name: channel.name, - }); - }); - - return { - success: true, - guild: { - id: guild.id, - name: guild.name, - icon: guild.icon, - // channel: "1162917335275950180", - channel: "", - channels, - }, - tzNames: moment.tz.names(), - }; -}; diff --git a/src/routes/api/config/index.tsx b/src/routes/api/config/index.tsx deleted file mode 100644 index 7dfc0c8..0000000 --- a/src/routes/api/config/index.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { getSession } from "@auth/solid-start"; -import { APIEvent } from "@solidjs/start/server/types"; -import { eq } from "drizzle-orm"; -import createClient from "openapi-fetch"; -import db from "~/drizzle"; -import { accounts } from "~/drizzle/schema"; -import { authOptions } from "~/server/auth"; -import { paths } from "~/types/discord"; - -type data = { - success: boolean | null; - guilds: { - id: string; - name: string; - icon: string | null | undefined; - }[]; -}; - -export const GET = async ( - event: APIEvent, -): Promise< - { success: false; message: string } | (data & { success: true }) -> => { - if (!event) return { success: false, message: "No request event!" }; - - const session = await getSession(event.request, authOptions); - if (!session?.user?.id) - return { success: false, message: "No user with id!" }; - - const { DISCORD_ACCESS_TOKEN } = ( - await db - .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token }) - .from(accounts) - .where(eq(accounts.userId, session.user?.id)) - .limit(1) - .execute() - )[0]; - if (!DISCORD_ACCESS_TOKEN) - return { success: false, message: "No discord access token!" }; - - const { GET } = createClient({ - baseUrl: "https://discord.com/api/v10", - }); - const { data: guilds, error } = await GET("/users/@me/guilds", { - headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` }, - }); - - if (error) { - console.log(error); - return { success: false, message: "Error on discord api request!" }; - } - - return { - success: true, - guilds: - guilds - ?.filter((e) => parseInt(e.permissions) & (1 << 5)) - .map(({ id, name, icon }) => ({ id, name, icon })) ?? [], - }; -}; diff --git a/src/routes/config/[guildId].tsx b/src/routes/config/[guildId].tsx index 75aefb9..9fd2fb3 100644 --- a/src/routes/config/[guildId].tsx +++ b/src/routes/config/[guildId].tsx @@ -1,5 +1,9 @@ +import { getSession } from "@auth/solid-start"; import { faToggleOff, faToggleOn } from "@fortawesome/pro-regular-svg-icons"; import { useLocation, useNavigate, useParams } from "@solidjs/router"; +import { eq } from "drizzle-orm"; +import moment from "moment-timezone"; +import createClient from "openapi-fetch"; import { For, Index, @@ -11,6 +15,10 @@ import { createStore } from "solid-js/store"; import { getRequestEvent } from "solid-js/web"; import { FontAwesomeIcon } from "~/components/FontAwesomeIcon"; import Layout from "~/components/Layout"; +import db from "~/drizzle"; +import { accounts } from "~/drizzle/schema"; +import { authOptions } from "~/server/auth"; +import { paths } from "~/types/discord"; import "../../styles/pages/config.scss"; const guessTZ = () => Intl.DateTimeFormat().resolvedOptions().timeZone; @@ -27,11 +35,102 @@ const initialValue = (params: ReturnType) => ({ tzNames: [guessTZ()], }); +const getPayload = async ( + id: string, + pathName: string, +): Promise< + | { success: false; message: string } + | (ReturnType & { success: true }) +> => { + "use server"; + + const event = getRequestEvent(); + if (!event) return { success: false, message: "No request event!" }; + + const session = await getSession(event.request, authOptions); + if (!session?.user?.id) + return { success: false, message: "No user with id!" }; + + const { DISCORD_ACCESS_TOKEN } = ( + await db + .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token }) + .from(accounts) + .where(eq(accounts.userId, session.user?.id)) + .limit(1) + .execute() + )[0]; + if (!DISCORD_ACCESS_TOKEN) + return { success: false, message: "No discord access token!" }; + + const { GET } = createClient({ + baseUrl: "https://discord.com/api/v10", + }); + const guildsRequest = await GET("/users/@me/guilds", { + headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` }, + }); + const channelsRequest = await GET("/guilds/{guild_id}/channels", { + params: { + path: { + guild_id: id, + }, + }, + headers: { Authorization: `Bot ${import.meta.env.VITE_DISCORD_BOT_TOKEN}` }, + }); + if (guildsRequest.error || channelsRequest.error) { + console.log(guildsRequest.error, channelsRequest.error, event.path); + return { + success: false, + message: "Error on one of the discord api requests!", + }; + } + + const guild = guildsRequest.data?.find((e) => e.id === id); + + if (!guild) + return { + success: false, + message: "User is in no such guild with requested id!", + }; + if (!(parseInt(guild.permissions) & (1 << 5))) + return { + success: false, + message: + "User is no MANAGE_GUILD permissions on this guild with requested id!", + }; + + let channels: ReturnType["guild"]["channels"] = []; + channelsRequest.data?.forEach((channel) => { + if (channel.type !== 0) return; + channels.push({ + id: channel.id, + name: channel.name, + }); + }); + + console.log( + pathName, + pathName == event.path ? "server" : "client", + "success", + ); + + return { + success: true, + guild: { + id: guild.id, + name: guild.name, + icon: guild.icon, + // channel: "1162917335275950180", + channel: "", + channels, + }, + tzNames: moment.tz.names(), + }; +}; + function config() { const params = useParams(); const navigator = useNavigate(); const location = useLocation(); - const event = getRequestEvent(); const [timezoneRef, setTimezoneRef] = createSignal(); const [timePlanningRef, setTimePlanningRef] = @@ -44,22 +143,9 @@ function config() { const [payload] = createResource( params.guildId, async (id) => { - const payload = await fetch(`http://localhost:3000/api/config/${id}`, { - headers: event?.headers, - }) - .then( - (res) => - res.json() as Promise< - | { - success: false; - message: string; - } - | (ReturnType & { - success: true; - }) - >, - ) - .catch((e) => console.warn(e, id)); + const payload = await getPayload(id, location.pathname).catch((e) => + console.warn(e, id), + ); if (!payload) { console.error(location.pathname, payload); diff --git a/src/routes/config/index.tsx b/src/routes/config/index.tsx index 278f8dc..528fa1d 100644 --- a/src/routes/config/index.tsx +++ b/src/routes/config/index.tsx @@ -1,13 +1,20 @@ +import { getSession } from "@auth/solid-start"; import { faBadgeCheck, faCircleExclamation, faPlus, } from "@fortawesome/pro-regular-svg-icons"; -import { useNavigate } from "@solidjs/router"; +import { useLocation, useNavigate } from "@solidjs/router"; +import { eq } from "drizzle-orm"; +import createClient from "openapi-fetch"; import { For, createResource } from "solid-js"; import { getRequestEvent } from "solid-js/web"; import { FontAwesomeIcon } from "~/components/FontAwesomeIcon"; import Layout from "~/components/Layout"; +import db from "~/drizzle"; +import { accounts } from "~/drizzle/schema"; +import { authOptions } from "~/server/auth"; +import { paths } from "~/types/discord"; import "../../styles/pages/config.scss"; const initialValue = () => ({ @@ -19,37 +26,76 @@ const initialValue = () => ({ }[], }); +const getPayload = async ( + pathName: string, +): Promise< + | { success: false; message: string } + | (ReturnType & { success: true }) +> => { + "use server"; + + const event = getRequestEvent(); + if (!event) return { success: false, message: "No request event!" }; + + const session = await getSession(event.request, authOptions); + if (!session?.user?.id) + return { success: false, message: "No user with id!" }; + + const { DISCORD_ACCESS_TOKEN } = ( + await db + .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token }) + .from(accounts) + .where(eq(accounts.userId, session.user?.id)) + .limit(1) + .execute() + )[0]; + if (!DISCORD_ACCESS_TOKEN) + return { success: false, message: "No discord access token!" }; + + const { GET } = createClient({ + baseUrl: "https://discord.com/api/v10", + }); + const { data: guilds, error } = await GET("/users/@me/guilds", { + headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` }, + }); + + if (error) { + console.log(error); + return { success: false, message: "Error on discord api request!" }; + } + console.log( + pathName, + pathName == event.path ? "server" : "client", + "success", + ); + + return { + success: true, + guilds: + guilds + ?.filter((e) => parseInt(e.permissions) & (1 << 5)) + .map(({ id, name, icon }) => ({ id, name, icon })) ?? [], + }; +}; + function index() { const navigator = useNavigate(); - const event = getRequestEvent(); + const location = useLocation(); const [payload] = createResource( // eslint-disable-next-line solid/reactivity async () => { - const payload = await fetch("http://localhost:3000/api/config", { - headers: event?.headers, - }) - .then( - (res) => - res.json() as Promise< - | { - success: false; - message: string; - } - | (ReturnType & { - success: true; - }) - >, - ) - .catch((e) => console.warn(e)); + const payload = await getPayload(location.pathname).catch((e) => + console.warn(e), + ); if (!payload) { - console.error("/config", payload); + console.error(location.pathname, payload); return initialValue(); } if (!payload.success) { - console.log("/config", payload.message, "No success"); + console.log(location.pathname, payload.message, "No success"); navigator("/", { replace: false }); return initialValue(); }