Skip to content

Commit

Permalink
feat: better organization in .env module
Browse files Browse the repository at this point in the history
wywailem env baseurl bo doslownie do niczego ona nie byla potrzebne, tylko robilismy z tego apps url wiec po prostu to dodalem do env, dzieki czemu moglem uzywac tego pliku tez po kliencie jak juz nie bylo eksportu serwerowego, do tego lepsze nazwy i mniej zmiennych w funkcjach w page.client
  • Loading branch information
qamarq committed Dec 15, 2024
1 parent 49c8c1b commit eaf094e
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 56 deletions.
4 changes: 2 additions & 2 deletions frontend/src/app/api/login/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { cookies as cookiesPromise } from "next/headers";
import { redirect } from "next/navigation";

import { USOS_APPS_URL } from "@/env.mjs";
import { env } from "@/env.mjs";
import { getRequestToken } from "@/lib/auth";

export const dynamic = "force-dynamic";
Expand Down Expand Up @@ -39,6 +39,6 @@ export async function GET() {
});

return redirect(
`${USOS_APPS_URL}/services/oauth/authorize?oauth_token=${token.token}`,
`${env.USOS_APPS_URL}/services/oauth/authorize?oauth_token=${token.token}`,
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,11 @@ interface PlanResponseType {
export const SyncErrorAlert = ({
onlinePlan,
planDate,
bounce = false,
downloadChanges,
sendChanges,
}: {
onlinePlan: PlanResponseType | null | undefined;
planDate: Date;
bounce?: boolean;
downloadChanges: () => void;
sendChanges: () => void;
}) => {
Expand Down Expand Up @@ -74,7 +72,6 @@ export const SyncErrorAlert = ({
<div
className={cn(
"flex w-full flex-col rounded-md bg-primary/10 transition-all",
{ "animate-fast-bounce": bounce },
)}
>
<div className="flex w-full items-start justify-start p-4 pb-2">
Expand Down
43 changes: 22 additions & 21 deletions frontend/src/app/plans/edit/[id]/_components/SyncedButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,43 +8,41 @@ import {
RefreshCwOffIcon,
} from "lucide-react";
import React, { useMemo } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import type { PlanState } from "@/lib/usePlan";

export const SyncedButton = ({
synced,
onlineId,
syncing,
plan,
isSyncing,
onClick,
bounceAlert,
equalsDates,
isEqualsDates,
isOffline,
}: {
synced: boolean;
onlineId: string | null;
syncing: boolean;
plan: PlanState;
isSyncing: boolean;
onClick: () => Promise<void>;
bounceAlert: () => void;
equalsDates: boolean;
isEqualsDates: boolean;
isOffline: boolean;
}) => {
const message = useMemo(() => {
if (synced && equalsDates) {
if (plan.synced && isEqualsDates) {
return "Zsynchronizowano";
} else if (!(onlineId ?? "")) {
} else if (!(plan.onlineId ?? "")) {
return "Plan dostępny tylko lokalnie";
} else if (syncing) {
} else if (isSyncing) {
return "Synchronizowanie...";
} else if (!equalsDates) {
} else if (!isEqualsDates) {
return "Twoja wersja różni się od wersji online";
}
return "Masz lokalne zmiany";
}, [synced, onlineId, syncing, equalsDates]);
}, [plan.synced, plan.onlineId, isSyncing, isEqualsDates]);
return (
<Tooltip>
<TooltipTrigger asChild={true}>
Expand All @@ -53,22 +51,25 @@ export const SyncedButton = ({
variant="outline"
className="min-w-10"
onClick={() => {
if (!equalsDates) {
bounceAlert();
if (!isEqualsDates) {
toast.info(
"Wybierz akcję z alertu powyżej, aby zsynchronizować dane tak jak chcesz",
{ duration: 5000 },
);
} else if (isOffline) {
return;
} else {
void onClick();
}
}}
>
{synced && equalsDates ? (
{plan.synced && isEqualsDates ? (
<CloudIcon className="size-4 text-emerald-500" />
) : !(onlineId ?? "") ? (
) : !(plan.onlineId ?? "") ? (
<AlertTriangleIcon className="size-4 text-rose-500" />
) : syncing ? (
) : isSyncing ? (
<RefreshCwIcon className="size-4 animate-spin text-primary" />
) : !equalsDates ? (
) : !isEqualsDates ? (
<GitPullRequestClosed className="size-4 text-primary" />
) : (
<RefreshCwOffIcon className="size-4 text-amber-500" />
Expand Down
22 changes: 6 additions & 16 deletions frontend/src/app/plans/edit/[id]/page.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { env } from "@/env.mjs";
import { usePlan } from "@/lib/usePlan";
import { registrationReplacer } from "@/lib/utils";
import { createOnlinePlan } from "@/lib/utils/createOnlinePlan";
Expand All @@ -49,7 +50,6 @@ export function CreateNewPlanPage({
}) {
const [syncing, setSyncing] = useState(false);
const [offlineAlert, setOfflineAlert] = useState(false);
const [bouncingAlert, setBouncingAlert] = useState(false);
const [faculty, setFaculty] = useState<string | null>(null);

const firstTime = useRef(true);
Expand All @@ -64,7 +64,7 @@ export function CreateNewPlanPage({
queryKey: ["registrations", faculty],
queryFn: async () => {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/departments/${faculty}/registrations`,
`${env.NEXT_PUBLIC_API_URL}/departments/${faculty}/registrations`,
);

if (!response.ok) {
Expand Down Expand Up @@ -101,7 +101,7 @@ export function CreateNewPlanPage({
mutationKey: ["courses"],
mutationFn: async (registrationId: string) => {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/departments/${faculty}/registrations/${encodeURIComponent(registrationId)}/courses`,
`${env.NEXT_PUBLIC_API_URL}/departments/${faculty}/registrations/${encodeURIComponent(registrationId)}/courses`,
);

if (!response.ok) {
Expand Down Expand Up @@ -176,13 +176,6 @@ export function CreateNewPlanPage({
}
};

const bounceAlert = () => {
setBouncingAlert(true);
setTimeout(() => {
setBouncingAlert(false);
}, 1000);
};

const resetInactivityTimer = () => {
if (inactivityTimeout.current !== null) {
clearTimeout(inactivityTimeout.current);
Expand Down Expand Up @@ -248,7 +241,6 @@ export function CreateNewPlanPage({
}}
planDate={plan.updatedAt}
onlinePlan={onlinePlan}
bounce={bouncingAlert}
/>

<div className="flex flex-col justify-start gap-3 md:w-full">
Expand Down Expand Up @@ -292,13 +284,11 @@ export function CreateNewPlanPage({
</form>
</div>
<SyncedButton
synced={plan.synced}
onlineId={plan.onlineId}
syncing={syncing}
bounceAlert={bounceAlert}
plan={plan}
isSyncing={syncing}
onClick={handleSyncPlan}
isOffline={offlineAlert}
equalsDates={isEqual(
isEqualsDates={isEqual(
plan.updatedAt,
new Date(onlinePlan ? onlinePlan.updatedAt : plan.updatedAt),
)}
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/app/plans/edit/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import React from "react";

import { env } from "@/env.mjs";

import { CreateNewPlanPage } from "./page.client";

interface PageProps {
Expand All @@ -19,7 +21,7 @@ export default async function CreateNewPlan({ params }: PageProps) {
}

const facultiesRes = (await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/departments`,
`${env.NEXT_PUBLIC_API_URL}/departments`,
).then((r) => r.json())) as Array<{ id: string; name: string }> | null;
if (!facultiesRes) {
return notFound();
Expand Down
6 changes: 2 additions & 4 deletions frontend/src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const env = createEnv({
server: {
USOS_CONSUMER_KEY: z.string().min(1),
USOS_CONSUMER_SECRET: z.string().min(1),
USOS_BASE_URL: z.string().startsWith("usos").default("usos.pwr.edu.pl"),
USOS_APPS_URL: z.string().url().default("https://apps.usos.pwr.edu.pl"),
SITE_URL: z.string().url().default("http://localhost:3000"),
NEXT_PUBLIC_API_URL: z.string().url().default("http://localhost:3000/api"),
},
Expand All @@ -15,11 +15,9 @@ export const env = createEnv({
runtimeEnv: {
SITE_URL: process.env.SITE_URL,
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
USOS_BASE_URL: process.env.USOS_BASE_URL,
USOS_APPS_URL: process.env.USOS_APPS_URL,
USOS_CONSUMER_KEY: process.env.USOS_CONSUMER_KEY,
USOS_CONSUMER_SECRET: process.env.USOS_CONSUMER_SECRET,
},
skipValidation: process.env.SKIP_ENV_VALIDATION === "true",
});

export const USOS_APPS_URL = `https://apps.${env.USOS_BASE_URL}`;
12 changes: 5 additions & 7 deletions frontend/src/lib/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const getAccessToken = async (
) => {
const data = oauth.authorize(
{
url: `https://apps.${env.USOS_BASE_URL}/services/oauth/access_token`,
url: `${env.USOS_APPS_URL}/services/oauth/access_token`,
method: "POST",
data: { oauth_token, oauth_verifier },
},
Expand All @@ -35,8 +35,8 @@ export const getAccessToken = async (
);

const response = await fetch(
`https://apps.${
env.USOS_BASE_URL
`${
env.USOS_APPS_URL
}/services/oauth/access_token?${new URLSearchParams(Object.entries(data)).toString()}
`,
{
Expand All @@ -62,7 +62,7 @@ const removeMultipleSlashesFromUrl = (url: string) => {

export async function getRequestToken() {
const data = oauth.authorize({
url: `https://apps.${env.USOS_BASE_URL}/services/oauth/request_token`,
url: `${env.USOS_APPS_URL}/services/oauth/request_token`,
method: "POST",
data: {
oauth_callback: removeMultipleSlashesFromUrl(
Expand All @@ -73,9 +73,7 @@ export async function getRequestToken() {
});

const response = await fetch(
`https://apps.${
env.USOS_BASE_URL
}/services/oauth/request_token?${new URLSearchParams(
`${env.USOS_APPS_URL}/services/oauth/request_token?${new URLSearchParams(
Object.entries(data),
).toString()}`,
{
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/services/usos/usosClient.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fetch from "node-fetch";

import { USOS_APPS_URL } from "@/env.mjs";
import { env } from "@/env.mjs";
import { oauth } from "@/lib/auth";

const baseUrl = `${USOS_APPS_URL}/services`;
const baseUrl = `${env.USOS_APPS_URL}/services`;

export const createClient = ({
token,
Expand Down

0 comments on commit eaf094e

Please sign in to comment.