Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add middleware utils #109

Merged
merged 5 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 25 additions & 77 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,105 +2,53 @@ import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

import {
IS_EXIST_PROBLEMS,
LOG_PARAMS,
UNSUB_PARAMS,
} from "@shared/constants/middlewareConstant";
import { API_ROUTE } from "@shared/remotes";
import { LogData } from "@shared/types";
import { undefined } from "zod";
import { articleMiddleware } from "@shared/middlewares/article";
import { MainMiddleware } from "@shared/middlewares/main";
import { problemMiddleware } from "@shared/middlewares/problem";
import { unsubscriptionMiddleware } from "@shared/middlewares/subscription";
import { workbookMiddleware } from "@shared/middlewares/workbook";

const withOutAuthList = [];
const withAuthList = [];

// NOTE : ์ธ์ฆ์—†์ด ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ํŽ˜์ด์ง€์— ๋Œ€ํ•œ middleware
const withOutAuth = async (req: NextRequest) => {
return NextResponse.next();
};

// NOTE : ์ธ์ฆ๊ธฐ๋ฐ˜ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ํŽ˜์ด์ง€์— ๋Œ€ํ•œ middleware
const withAuth = async (req: NextRequest) => {
return NextResponse.next();
};

export default async function middleware(req: NextRequest) {
const isWithAuth = true;
const isWithOutAuth = false;

const nextUrl = req.nextUrl.clone();
const { pathname, searchParams } = nextUrl;
const email = searchParams.get("user");
const articleId = searchParams.get("articleId");
const workbookId = searchParams.get("workbookId");
const fromEmail = searchParams.get(LOG_PARAMS.FROM_EMAIL);

if (pathname === "/") {
return NextResponse.redirect(
"https://fewletter.notion.site/FEW-a87459feb21246b0bc63c68ef6140645",
);
return MainMiddleware()
}

/** /workbook ์œผ๋กœ ์ง„์ž… ์‹œ ๋ฆฌ๋‹ค์ด๋ž™์…˜ */
if (pathname === "/workbook") {
nextUrl.pathname = "/workbook/1";
return NextResponse.redirect(nextUrl);
return workbookMiddleware({ nextUrl })
}

/** unsubscribe page ์ง„์ž… ์‹œ ์ด๋ฉ”์ผ, ์•„ํ‹ฐํด ์•„์ด๋””, ์›Œํฌ๋ถ ์•„์ด๋”” ์ฟ ํ‚ค์— ์ €์žฅํ•˜๋Š” ๋กœ์ง */
if (email && articleId && workbookId) {
// UNSUB_PARAMS์˜ ๊ฐ’์„ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ฒ˜๋ฆฌ
const paramsToDelete = Object.values(UNSUB_PARAMS);

// searchParams.delete ๋ฐ˜๋ณต์ ์œผ๋กœ ํ˜ธ์ถœ
paramsToDelete.map((param) => {
nextUrl.searchParams.delete(param);
});
const decodedEmail = decodeURIComponent(email);

// Store the email in a cookie to pass to the page
const response = NextResponse.redirect(nextUrl);
response.cookies.set("user-email", decodedEmail);
response.cookies.set(UNSUB_PARAMS.ARTICLE_ID, articleId);
response.cookies.set(UNSUB_PARAMS.WORKBOOK_ID, workbookId);

return response;
if (pathname.includes("/unsubscribe")) {
return unsubscriptionMiddleware({ nextUrl })
}

/** article url ์ง„์ž…์‹œ ์ด๋ฉ”์ผ ๋กœ๊ทธ ์Œ“๋Š” ๋กœ์ง */
if (pathname.includes("/article") && fromEmail) {
try {
const history: LogData = {
from: "email",
to: "readArticle",
};
await fetch(
`${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ROUTE.LOGS()}`,
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
history: JSON.stringify(history),
}),
},
);
nextUrl.searchParams.delete(LOG_PARAMS.FROM_EMAIL);
return NextResponse.redirect(nextUrl);
} catch (error) {
return undefined;
}
if (pathname.includes("/article")) {
return articleMiddleware({ nextUrl })
}
if (pathname.includes("/problem") && !articleId) {
/** problme url ์ง„์ž…์‹œ ์ „์—ญ์ƒํƒœ ์—†์œผ๋ฉด ๋“ค์–ด์˜ฌ ์ˆ˜ ์—†๊ฒŒ ๋ฐฉ์–ดํ•˜๋Š” ๋กœ์ง */
const isProblemIds = req.cookies.get(IS_EXIST_PROBLEMS)?.value === "true";

if (!isProblemIds) {
nextUrl.pathname = "/";
return NextResponse.redirect(nextUrl);
}
if (pathname.includes("/problem")) {
return problemMiddleware({ req, nextUrl })
}

};

// NOTE : ์ธ์ฆ๊ธฐ๋ฐ˜ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ํŽ˜์ด์ง€์— ๋Œ€ํ•œ middleware
const withAuth = async (req: NextRequest) => {
return NextResponse.next();
};

export default async function middleware(req: NextRequest) {
const isWithAuth = false;
const isWithOutAuth = true;

if (isWithAuth) return withAuth(req);
if (isWithOutAuth) return withOutAuth(req);

Expand Down
43 changes: 43 additions & 0 deletions src/shared/middlewares/article.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { NextURL } from "next/dist/server/web/next-url";
import { NextResponse } from "next/server";

import { LOG_PARAMS } from "@shared/constants/middlewareConstant";
import { API_ROUTE } from "@shared/remotes";
import { LogData } from "@shared/types";

type articleMiddlewareProps = {
nextUrl: NextURL;
};

const setArticleLogs = async ({ nextUrl }: articleMiddlewareProps) => {
try {
const history: LogData = {
from: "email",
to: "readArticle",
};
await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ROUTE.LOGS()}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
history: JSON.stringify(history),
}),
});
nextUrl.searchParams.delete(LOG_PARAMS.FROM_EMAIL);
return NextResponse.redirect(nextUrl);
} catch (error) {
return undefined;
}
};

export const articleMiddleware = ({ nextUrl }: articleMiddlewareProps) => {
const { searchParams } = nextUrl;

const fromEmail = searchParams.get(LOG_PARAMS.FROM_EMAIL);

if (fromEmail) {
return setArticleLogs({ nextUrl });
}
};
11 changes: 11 additions & 0 deletions src/shared/middlewares/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";

const redirectToMain = () => {
return NextResponse.redirect(
"https://fewletter.notion.site/FEW-a87459feb21246b0bc63c68ef6140645",
);
};

export const MainMiddleware = () => {
return redirectToMain()
}
29 changes: 29 additions & 0 deletions src/shared/middlewares/problem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { NextURL } from "next/dist/server/web/next-url";
import { NextRequest, NextResponse } from "next/server";

import { IS_EXIST_PROBLEMS } from "@shared/constants/middlewareConstant";

type problemMiddlewareProps = {
req: NextRequest;
nextUrl: NextURL;
};

const redirectProblemNotExist = ({
req,
nextUrl,
}: problemMiddlewareProps) => {
/** problme url ์ง„์ž…์‹œ ์ „์—ญ์ƒํƒœ ์—†์œผ๋ฉด ๋“ค์–ด์˜ฌ ์ˆ˜ ์—†๊ฒŒ ๋ฐฉ์–ดํ•˜๋Š” ๋กœ์ง */
const isProblemIds = req.cookies.get(IS_EXIST_PROBLEMS)?.value === "true";

if (!isProblemIds) {
nextUrl.pathname = "/";
return NextResponse.redirect(nextUrl);
}
};

export const problemMiddleware = ({
req,
nextUrl,
}: problemMiddlewareProps) => {
return redirectProblemNotExist({ req, nextUrl })
}
53 changes: 53 additions & 0 deletions src/shared/middlewares/subscription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { NextURL } from "next/dist/server/web/next-url";
import { NextResponse } from "next/server";

import { UNSUB_PARAMS } from "@shared/constants/middlewareConstant";

type saveUserInfoParams = {
email: string;
articleId: string;
workbookId: string;
nextUrl: NextURL;
};

type subscriptionMiddlewareProps = Pick<saveUserInfoParams, "nextUrl">;

const saveUnsubscribeUserInfo = ({
email,
articleId,
workbookId,
nextUrl,
}: saveUserInfoParams) => {
// UNSUB_PARAMS์˜ ๊ฐ’์„ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ฒ˜๋ฆฌ
const paramsToDelete = Object.values(UNSUB_PARAMS);

// searchParams.delete ๋ฐ˜๋ณต์ ์œผ๋กœ ํ˜ธ์ถœ
paramsToDelete.map((param) => {
nextUrl.searchParams.delete(param);
});
const decodedEmail = decodeURIComponent(email);

// Store the email in a cookie to pass to the page
const response = NextResponse.redirect(nextUrl);
response.cookies.set("user-email", decodedEmail);
response.cookies.set(UNSUB_PARAMS.ARTICLE_ID, articleId);
response.cookies.set(UNSUB_PARAMS.WORKBOOK_ID, workbookId);

return response;
};

export const unsubscriptionMiddleware = ({
nextUrl,
}: subscriptionMiddlewareProps) => {
const { searchParams } = nextUrl;

const email = searchParams.get("user");
const articleId = searchParams.get("articleId");
const workbookId = searchParams.get("workbookId");

if (email && articleId && workbookId) {
return saveUnsubscribeUserInfo({ email, articleId, workbookId, nextUrl });
}

return NextResponse.next()
};
15 changes: 15 additions & 0 deletions src/shared/middlewares/workbook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { NextURL } from "next/dist/server/web/next-url";
import { NextResponse } from "next/server";

type workbookMiddlewareProps = {
nextUrl: NextURL
}

const redirectToWorkbook = ({ nextUrl }: workbookMiddlewareProps) => {
nextUrl.pathname = "/workbook/1";
return NextResponse.redirect(nextUrl);
}

export const workbookMiddleware = ({ nextUrl }: workbookMiddlewareProps) => {
return redirectToWorkbook({ nextUrl })
}
Loading