Chore: Revert to 'use server' functions

This commit is contained in:
Aron Malcher 2024-02-11 23:22:13 +01:00
parent 2b9b5198fa
commit 590e7d8265
Signed by: aronmal
GPG key ID: 816B7707426FC612
5 changed files with 171 additions and 203 deletions

View file

@ -42,6 +42,8 @@ async function getUser() {
.execute() .execute()
)[0]; )[0];
console.log("userInfo", "success");
return { success: true, message: "", ...user }; return { success: true, message: "", ...user };
} }

View file

@ -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<paths>({
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(),
};
};

View file

@ -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<paths>({
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 })) ?? [],
};
};

View file

@ -1,5 +1,9 @@
import { getSession } from "@auth/solid-start";
import { faToggleOff, faToggleOn } from "@fortawesome/pro-regular-svg-icons"; import { faToggleOff, faToggleOn } from "@fortawesome/pro-regular-svg-icons";
import { useLocation, useNavigate, useParams } from "@solidjs/router"; import { useLocation, useNavigate, useParams } from "@solidjs/router";
import { eq } from "drizzle-orm";
import moment from "moment-timezone";
import createClient from "openapi-fetch";
import { import {
For, For,
Index, Index,
@ -11,6 +15,10 @@ import { createStore } from "solid-js/store";
import { getRequestEvent } from "solid-js/web"; import { getRequestEvent } from "solid-js/web";
import { FontAwesomeIcon } from "~/components/FontAwesomeIcon"; import { FontAwesomeIcon } from "~/components/FontAwesomeIcon";
import Layout from "~/components/Layout"; 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"; import "../../styles/pages/config.scss";
const guessTZ = () => Intl.DateTimeFormat().resolvedOptions().timeZone; const guessTZ = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
@ -27,11 +35,102 @@ const initialValue = (params: ReturnType<typeof useParams>) => ({
tzNames: [guessTZ()], tzNames: [guessTZ()],
}); });
const getPayload = async (
id: string,
pathName: string,
): Promise<
| { success: false; message: string }
| (ReturnType<typeof initialValue> & { 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<paths>({
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<typeof initialValue>["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() { function config() {
const params = useParams(); const params = useParams();
const navigator = useNavigate(); const navigator = useNavigate();
const location = useLocation(); const location = useLocation();
const event = getRequestEvent();
const [timezoneRef, setTimezoneRef] = createSignal<HTMLInputElement>(); const [timezoneRef, setTimezoneRef] = createSignal<HTMLInputElement>();
const [timePlanningRef, setTimePlanningRef] = const [timePlanningRef, setTimePlanningRef] =
@ -44,22 +143,9 @@ function config() {
const [payload] = createResource( const [payload] = createResource(
params.guildId, params.guildId,
async (id) => { async (id) => {
const payload = await fetch(`http://localhost:3000/api/config/${id}`, { const payload = await getPayload(id, location.pathname).catch((e) =>
headers: event?.headers, console.warn(e, id),
}) );
.then(
(res) =>
res.json() as Promise<
| {
success: false;
message: string;
}
| (ReturnType<typeof initialValue> & {
success: true;
})
>,
)
.catch((e) => console.warn(e, id));
if (!payload) { if (!payload) {
console.error(location.pathname, payload); console.error(location.pathname, payload);

View file

@ -1,13 +1,20 @@
import { getSession } from "@auth/solid-start";
import { import {
faBadgeCheck, faBadgeCheck,
faCircleExclamation, faCircleExclamation,
faPlus, faPlus,
} from "@fortawesome/pro-regular-svg-icons"; } 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 { For, createResource } from "solid-js";
import { getRequestEvent } from "solid-js/web"; import { getRequestEvent } from "solid-js/web";
import { FontAwesomeIcon } from "~/components/FontAwesomeIcon"; import { FontAwesomeIcon } from "~/components/FontAwesomeIcon";
import Layout from "~/components/Layout"; 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"; import "../../styles/pages/config.scss";
const initialValue = () => ({ const initialValue = () => ({
@ -19,37 +26,76 @@ const initialValue = () => ({
}[], }[],
}); });
const getPayload = async (
pathName: string,
): Promise<
| { success: false; message: string }
| (ReturnType<typeof initialValue> & { 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<paths>({
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() { function index() {
const navigator = useNavigate(); const navigator = useNavigate();
const event = getRequestEvent(); const location = useLocation();
const [payload] = createResource( const [payload] = createResource(
// eslint-disable-next-line solid/reactivity // eslint-disable-next-line solid/reactivity
async () => { async () => {
const payload = await fetch("http://localhost:3000/api/config", { const payload = await getPayload(location.pathname).catch((e) =>
headers: event?.headers, console.warn(e),
}) );
.then(
(res) =>
res.json() as Promise<
| {
success: false;
message: string;
}
| (ReturnType<typeof initialValue> & {
success: true;
})
>,
)
.catch((e) => console.warn(e));
if (!payload) { if (!payload) {
console.error("/config", payload); console.error(location.pathname, payload);
return initialValue(); return initialValue();
} }
if (!payload.success) { if (!payload.success) {
console.log("/config", payload.message, "No success"); console.log(location.pathname, payload.message, "No success");
navigator("/", { replace: false }); navigator("/", { replace: false });
return initialValue(); return initialValue();
} }