Skip to content

Commit

Permalink
Create urlFromServer server action and replace fetch in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
pheralb committed Mar 30, 2024
1 parent 93b15e4 commit 9aece2a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import NextAuth from "next-auth";
import authConfig from "@/auth.config";

import { NextResponse } from "next/server";

import {
DEFAULT_LOGIN_REDIRECT_URL,
apiAuthPrefix,
Expand All @@ -9,6 +11,7 @@ import {
protectedRoutes,
publicRoutes,
} from "./routes";
import { urlFromServer } from "./server/actions/redirect";

const { auth } = NextAuth(authConfig);

Expand All @@ -33,7 +36,7 @@ export default auth(async (req) => {
// ⚙️ Is Auth Route. First, check is authenticated:
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(
return NextResponse.redirect(
new URL(DEFAULT_LOGIN_REDIRECT_URL, nextUrl),
);
}
Expand All @@ -42,7 +45,7 @@ export default auth(async (req) => {

// ⚙️ If Slug contains ``c``, redirect to /check/:slug:
if (slugRoute?.endsWith("&c")) {
return Response.redirect(
return NextResponse.redirect(
new URL(`/check/${slugRoute.replace("&c", "")}`, nextUrl),
);
}
Expand All @@ -54,7 +57,7 @@ export default auth(async (req) => {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return Response.redirect(
return NextResponse.redirect(
new URL(`/auth?callbackUrl=${encodedCallbackUrl}`, nextUrl),
);
}
Expand All @@ -63,18 +66,17 @@ export default auth(async (req) => {
// If not public route and not protected route:
if (!isPublicRoute && !isProtectedRoute && !isCheckRoute) {
try {
const getDataApi = await fetch(
`${req.nextUrl.origin}/api/url?slug=${slugRoute}`,
);
const getDataApi = await urlFromServer(slugRoute!);

if (getDataApi.status === 404) {
return;
if (getDataApi.error) {
return NextResponse.json(
{ error: `Error: ${getDataApi.message}` },
{ status: 500 },
);
}

const getDataUrl = await getDataApi.json();

if (getDataUrl?.url) {
return Response.redirect(new URL(getDataUrl.url as string).toString());
if (getDataApi.url) {
return NextResponse.redirect(new URL(getDataApi.url).toString());
}
} catch (error) {
console.error("🚧 Error fetching slug: ", error);
Expand Down
51 changes: 51 additions & 0 deletions src/server/actions/redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"use server";

import { db } from "@/server/db";

interface urlFromServerResult {
error: boolean;
message: string;
url?: string;
}

export const urlFromServer = async (
slug: string,
): Promise<urlFromServerResult> => {
try {
const getLinkFromServer = await db.links.findUnique({
where: {
slug: slug,
},
});

if (!getLinkFromServer) {
return {
error: true,
message: "🚧 Error (urlFromServer): Slug not found or invalid.",
};
}

await db.links.update({
where: {
id: getLinkFromServer.id,
},
data: {
clicks: {
increment: 1,
},
},
});

return {
error: false,
message: "Success",
url: getLinkFromServer.url,
};
} catch (error) {
console.error("🚧 Error (urlFromServer): ", error);
return {
error: true,
message: "Something went wrong.",
};
}
};

0 comments on commit 9aece2a

Please sign in to comment.