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

Refacto: Refacto API to App router #146

Draft
wants to merge 22 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
10 changes: 10 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ const nextConfig = {
serverActions: true,
serverComponentsExternalPackages: ['mjml', 'mjml-react'],
},

webpack: (config, { isServer }) => {
// to use metascraper in route handlers https://github.com/uhop/node-re2/issues/63#issuecomment-1785743859
config.module.rules.push({
test: /\.node$/,
loader: 'node-loader',
});

return config;
},
reactStrictMode: false,
};

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"next-connect": "^1.0.0-next.3",
"next-contentlayer": "^0.3.2",
"next-superjson-plugin": "^0.5.8",
"node-loader": "^2.0.0",
"nodemailer": "^6.9.1",
"openai": "^4.10.0",
"plaiceholder": "^2.5.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app/(admin)/admin/[[...nextadmin]]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import schema from '@/../prisma/json-schema/json-schema.json';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import Dashboard, { DashboardProps } from '@/components/admin/Dashboard';
import {
linksByDay,
Expand All @@ -7,7 +8,6 @@ import {
newUsersByMonth,
} from '@/lib/adminQueries';
import client from '@/lib/db';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { options } from '@/utils/nextadmin';
import { NextAdmin, PageProps } from '@premieroctet/next-admin';
import { getNextAdminProps } from '@premieroctet/next-admin/dist/appRouter';
Expand Down
2 changes: 1 addition & 1 deletion src/app/(app)/(routes)/teams/[teamSlug]/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import authOptions from '@/app/api/auth/[...nextauth]/options';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';

export default async function Layout({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import TeamInfo from '@/components/teams/form/settings/TeamInfo';
import React from 'react';
import { TeamPageProps } from '../../page';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import SettingsPageLayout from '@/components/teams/form/settings/SettingsPageLayout';
import TeamInfo from '@/components/teams/form/settings/TeamInfo';
import { routes } from '@/core/constants';
import { getCurrentUser } from '@/lib/sessions';
import { checkUserTeamBySlug } from '@/services/database/user';
import { getTeamSettingsPageInfo } from '@/utils/page';
import Link from 'next/link';
import { checkUserTeamBySlug } from '@/services/database/user';
import { redirect } from 'next/navigation';
import { TeamPageProps } from '../../page';

export default async function Page({ params }: TeamPageProps) {
const teamSlug = params.teamSlug;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import React from 'react';
import { TeamPageProps } from '../../page';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';
import TeamIntegrations from '@/components/teams/form/settings/TeamIntegrations';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import SettingsPageLayout from '@/components/teams/form/settings/SettingsPageLayout';
import TeamIntegrations from '@/components/teams/form/settings/TeamIntegrations';
import { routes } from '@/core/constants';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { getCurrentUser } from '@/lib/sessions';
import { checkUserTeamBySlug } from '@/services/database/user';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { redirect } from 'next/navigation';
import { TeamPageProps } from '../../page';

export default async function Page({ params }: TeamPageProps) {
const teamSlug = params.teamSlug;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import React from 'react';
import { TeamPageProps } from '../../page';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';
import TeamUsers from '@/components/teams/form/settings/TeamUsers';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import SettingsPageLayout from '@/components/teams/form/settings/SettingsPageLayout';
import TeamUsers from '@/components/teams/form/settings/TeamUsers';
import { routes } from '@/core/constants';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { getTeamMembers } from '@/services/database/membership';
import { getCurrentUser } from '@/lib/sessions';
import { getTeamInvitations } from '@/services/database/invitation';
import { getTeamMembers } from '@/services/database/membership';
import { getTeamSubscriptions } from '@/services/database/subscription';
import { checkUserTeamBySlug } from '@/services/database/user';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { redirect } from 'next/navigation';
import { TeamPageProps } from '../../page';

export default async function Page({ params }: TeamPageProps) {
const teamSlug = params.teamSlug;
Expand Down
6 changes: 3 additions & 3 deletions src/app/(app)/(routes)/teams/[teamSlug]/settings/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import authOptions from '@/app/api/auth/[...nextauth]/options';
import { routes } from '@/core/constants';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { checkUserTeamBySlug } from '@/services/database/user';
import { notFound, redirect } from 'next/navigation';
import { TeamPageProps } from '../page';
import { routes } from '@/core/constants';
import { checkUserTeamBySlug } from '@/services/database/user';

const TeamSettingsPage = async ({ params }: TeamPageProps) => {
const teamSlug = params.teamSlug;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import React from 'react';
import { TeamPageProps } from '../../page';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';
import TeamTemplates from '@/components/teams/form/settings/TeamTemplates';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import SettingsPageLayout from '@/components/teams/form/settings/SettingsPageLayout';
import TeamTemplates from '@/components/teams/form/settings/TeamTemplates';
import { routes } from '@/core/constants';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { getCurrentUser } from '@/lib/sessions';
import { getTeamDigests } from '@/services/database/digest';
import { checkUserTeamBySlug } from '@/services/database/user';
import { getTeamSettingsPageInfo } from '@/utils/page';
import { redirect } from 'next/navigation';
import { TeamPageProps } from '../../page';

export default async function Page({ params }: TeamPageProps) {
const teamSlug = params.teamSlug;
Expand Down
2 changes: 1 addition & 1 deletion src/app/(app)/(routes)/teams/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import authOptions from '@/app/api/auth/[...nextauth]/options';
import { getCurrentUser } from '@/lib/sessions';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { redirect } from 'next/navigation';

export default async function Layout({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import schema from '@/../prisma/json-schema/json-schema.json';
import authOptions from '@/app/api/auth/[...nextauth]/options';
import client from '@/lib/db';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { options } from '@/utils/nextadmin';
import { createHandler } from '@premieroctet/next-admin/dist/appHandler';
import { getServerSession } from 'next-auth';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { EMAIL_SUBJECTS, sendEmail } from '@/emails';
import LoginEmail from '@/emails/templates/LoginEmail';
import prisma from '@/lib/db';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import NextAuth, { NextAuthOptions } from 'next-auth';
import { AuthOptions } from 'next-auth';
import EmailProvider from 'next-auth/providers/email';

export const authOptions: NextAuthOptions = {
const options: AuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
EmailProvider({
Expand All @@ -23,12 +23,12 @@ export const authOptions: NextAuthOptions = {
session: async ({ session, user }) => {
if (user) {
session.user.id = user.id;
session.user.email = user.email;

if (user.role) {
session.user.role = user.role;
}
}

return session;
},
},
Expand All @@ -37,4 +37,4 @@ export const authOptions: NextAuthOptions = {
},
};

export default NextAuth(authOptions);
export default options;
6 changes: 6 additions & 0 deletions src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import NextAuth from 'next-auth';
import options from './options';

const handler = NextAuth(options);

export { handler as GET, handler as POST };
55 changes: 55 additions & 0 deletions src/app/api/bookmark/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import db from '@/lib/db';
import { saveBookmark } from '@/services/database/bookmark';
import { HandlerApiError, HandlerApiResponse } from '@/utils/handlerResponse';

import { Bookmark } from '@prisma/client';
import jwt from 'jsonwebtoken';
import { NextRequest } from 'next/server';

export type ApiBookmarkResponseSuccess = Bookmark;

// export const router = createRouter<AuthApiRequest, NextApiResponse>();

// const UNIQUE_TOKEN_PER_INTERVAL = 500; // 500 requests
// const INTERVAL = 60000; // 1 minute
// interface PostRequestBody {
// linkUrl: string;
// }

// const limiter = rateLimit({
// uniqueTokenPerInterval: UNIQUE_TOKEN_PER_INTERVAL,
// interval: INTERVAL,
// });

export async function POST(req: NextRequest) {
try {
const { JWT_SECRET } = process.env;
const authHeader = req.headers.get('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) throw new Error();
if (!JWT_SECRET) return HandlerApiError.unauthorized();
const token = authHeader.substring(7, authHeader.length);
const decoded = jwt.verify(token, JWT_SECRET);
if (!decoded) return HandlerApiError.unauthorized();

const { teamId } = decoded as { teamId: string };
if (!teamId) return HandlerApiError.internalServerError();

const { linkUrl } = (await req.json()) as { linkUrl: string };
if (!linkUrl) return HandlerApiError.missingParameters();

// @todo implement rate limiting

const team = await db.team.findFirst({
where: {
id: teamId,
},
});
if (!team) throw new Error();
const bookmark = await saveBookmark(linkUrl, teamId);
return HandlerApiResponse.success(bookmark);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
return HandlerApiError.internalServerError();
}
}
24 changes: 24 additions & 0 deletions src/app/api/tags/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { NextRequest } from 'next/server';

import db from '@/lib/db';
import { HandlerApiError, HandlerApiResponse } from '@/utils/handlerResponse';

export async function GET(req: NextRequest) {
try {
/** Get all available tags */
const tags = await db.tag.findMany({
select: {
id: true,
name: true,
slug: true,
description: true,
},
});

return HandlerApiResponse.success(tags);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
return HandlerApiError.internalServerError();
}
}
48 changes: 48 additions & 0 deletions src/app/api/teams/[teamId]/bookmark/[bookmarkId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import db from '@/lib/db';
import { checkTeamAppRouter } from '@/lib/middleware';
import { HandlerApiError, HandlerApiResponse } from '@/utils/handlerResponse';
import { Bookmark } from '@prisma/client';
import { createEdgeRouter } from 'next-connect';
import { NextRequest } from 'next/server';

export type ResponseSuccess = Bookmark;

export interface TeamsRequestContext {
params: {
teamId: string;
bookmarkId?: string;
};

// Not the best way to do this but it works for now
// We need the middleware to set these values
// Right now next-connect doesn't support generics to enrich the request (https://github.com/hoangvvo/next-connect/issues/230)
membershipId: string;
teamId: string;
user: { id: string; email: string };
}

const router = createEdgeRouter<NextRequest, TeamsRequestContext>();

router.use(checkTeamAppRouter).delete(async (req, event, next) => {
const bookmarkId = event.params.bookmarkId as string;
const teamId = event.params.teamId as string;
try {
const bookmark = await db.bookmark.findFirstOrThrow({
where: { id: bookmarkId, teamId },
});

const deletedBookmark = await db.bookmark.delete({
where: { id: bookmark.id },
});

return HandlerApiResponse.success(deletedBookmark);
} catch (error: unknown) {
// eslint-disable-next-line no-console
console.log(error);
return HandlerApiError.internalServerError();
}
});

export async function DELETE(request: NextRequest, ctx: TeamsRequestContext) {
return router.run(request, ctx) as Promise<Response>;
}
59 changes: 59 additions & 0 deletions src/app/api/teams/[teamId]/bookmark/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { checkTeamAppRouter } from '@/lib/middleware';
import messages from '@/messages/en';
import { saveBookmark } from '@/services/database/bookmark';
import { HandlerApiError, HandlerApiResponse } from '@/utils/handlerResponse';
import { Bookmark } from '@prisma/client';
import * as Sentry from '@sentry/nextjs';
import { createEdgeRouter } from 'next-connect';
import type { NextRequest } from 'next/server';

export type ApiBookmarkResponseSuccess = Bookmark;

export interface TeamsRequestContext {
params: {
teamId: string;
};

// Not the best way to do this but it works for now
// We need the middleware to set these values
// Right now next-connect doesn't support generics to enrich the request (https://github.com/hoangvvo/next-connect/issues/230)
membershipId: string;
teamId: string;
user: { id: string; email: string };
}

const router = createEdgeRouter<NextRequest, TeamsRequestContext>();

router.use(checkTeamAppRouter).post(async (req, event, next) => {
const body = await req.json();
const linkUrl = body.link as string;
try {
const teamId = event.params.teamId as string;
const membershipId = event.membershipId as string;

if (!linkUrl) {
return HandlerApiError.badRequest();
}

const bookmark = await saveBookmark(linkUrl, teamId, membershipId);
return HandlerApiResponse.success(bookmark);
} catch (error: unknown) {
const error_code = (error as TypeError)
.message as keyof typeof messages.bookmark.create.error;

Sentry.captureMessage(
`Failed to save bookmark. Cause: ${
messages.bookmark.create.error[error_code] ??
(error as TypeError).message
} (${linkUrl})`
);

// eslint-disable-next-line no-console
console.log(error);
return HandlerApiError.internalServerError();
}
});

export async function POST(request: NextRequest, ctx: TeamsRequestContext) {
return router.run(request, ctx) as Promise<Response>;
}
Loading
Loading