Skip to content

Commit

Permalink
cleanup api
Browse files Browse the repository at this point in the history
  • Loading branch information
RealFascinated committed Mar 7, 2025
1 parent 648a891 commit 1b02c75
Show file tree
Hide file tree
Showing 8 changed files with 251 additions and 231 deletions.
77 changes: 33 additions & 44 deletions src/app/api/user/config/sharex/route.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,40 @@
import { authError } from "@/lib/api-commons";
import { auth } from "@/lib/auth";
import { handleApiRequestWithUser } from "@/lib/api-commons";
import { env } from "@/lib/env";
import { ApiErrorResponse, ApiSuccessResponse } from "@/type/api/responses";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
request: Request
): Promise<NextResponse<ApiSuccessResponse | ApiErrorResponse>> {
const requestHeaders = await headers();
const session = await auth.api.getSession({
headers: requestHeaders,
});
if (!session) {
return authError;
}
export async function GET(request: NextRequest): Promise<NextResponse> {
return handleApiRequestWithUser(async (user) => {
if (!user.uploadToken) {
return NextResponse.json(
{
message: "You do not have an upload token",
},
{ status: 400 }
);
}

if (!session.user.uploadToken) {
return NextResponse.json(
JSON.stringify({
Version: "14.1.0",
Name: `${env.NEXT_PUBLIC_WEBSITE_NAME}`,
DestinationType: "ImageUploader, TextUploader, FileUploader",
RequestMethod: "POST",
RequestURL: `${env.NEXT_PUBLIC_WEBSITE_URL}/api/upload/sharex`,
Body: "MultipartFormData",
Arguments: {
token: `${user.uploadToken}`,
},
FileFormName: "sharex",
URL: "{json:url}/{json:path}",
DeletionURL: "{json:deletionUrl}",
ErrorMessage: "{json:message}",
}),
{
message: "You do not have an upload token",
},
{ status: 400 }
status: 200,
headers: {
"Content-Disposition": `attachment; filename="sharex-config-${user.name}.sxcu"`,
},
}
);
}

return NextResponse.json(
JSON.parse(`{
"Version": "14.1.0",
"Name": "${env.NEXT_PUBLIC_WEBSITE_NAME}",
"DestinationType": "ImageUploader, TextUploader, FileUploader",
"RequestMethod": "POST",
"RequestURL": "${env.NEXT_PUBLIC_WEBSITE_URL}/api/upload/sharex",
"Body": "MultipartFormData",
"Arguments": {
"token": "${session.user.uploadToken}"
},
"FileFormName": "sharex",
"URL": "{json:url}/{json:path}",
"DeletionURL": "{json:deletionUrl}",
"ErrorMessage": "{json:message}"
}`),
{
status: 200,
headers: {
"Content-Disposition": `attachment; filename="sharex-config-${session.user.name}.sxcu"`,
},
}
);
});
}
87 changes: 45 additions & 42 deletions src/app/api/user/file/delete/[key]/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { notFound } from "@/lib/api-commons";
import { handleApiRequest, notFound } from "@/lib/api-commons";
import { UserType } from "@/lib/db/schemas/auth-schema";
import { getFileByDeleteKey, removeFile } from "@/lib/helpers/file";
import { getUserById } from "@/lib/helpers/user";
Expand All @@ -7,59 +7,62 @@ import { Notifications } from "@/lib/notification";
import { getFileName } from "@/lib/utils/file";
import { getFileThumbnailPath } from "@/lib/utils/paths";
import { storage } from "@/storage/create-storage";
import { ApiErrorResponse, ApiSuccessResponse } from "@/type/api/responses";
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
request: Request,
request: NextRequest,
{ params }: { params: Promise<{ key: string }> }
): Promise<NextResponse<ApiSuccessResponse | ApiErrorResponse>> {
const { key } = await params;
const file = await getFileByDeleteKey(key);
if (!file) {
return notFound;
}
const user: UserType | undefined = await getUserById(file.userId);
if (!user) {
return notFound;
}
): Promise<NextResponse> {
return handleApiRequest(async () => {
const { key } = await params;
const file = await getFileByDeleteKey(key);
if (!file) {
return notFound;
}
const user: UserType | undefined = await getUserById(file.userId);
if (!user) {
return notFound;
}

try {
const deletedFile = await storage.deleteFile(getFileName(file));
if (!deletedFile) {
return NextResponse.json(
{ message: "Unable to delete the file, please contact an admin" },
{ status: 500 }
try {
const deletedFile = await storage.deleteFile(getFileName(file));
if (!deletedFile) {
return NextResponse.json(
{ message: "Unable to delete the file, please contact an admin" },
{ status: 500 }
);
}
const deletedThubnail = await storage.deleteFile(
getFileThumbnailPath(file.userId, file)
);
}
const deletedThubnail = await storage.deleteFile(
getFileThumbnailPath(file.userId, file)
);
if (!deletedThubnail) {
if (!deletedThubnail) {
return NextResponse.json(
{
message: "Unable to delete the thumbnail, please contact an admin",
},
{ status: 500 }
);
}
await removeFile(file.id);

Notifications.sendDeleteFileNotification(user, file);
} catch {
return NextResponse.json(
{ message: "Unable to delete the thumbnail, please contact an admin" },
{
message:
"An error occured when removing this file, please contact an admin",
},
{ status: 500 }
);
}
await removeFile(file.id);

Notifications.sendDeleteFileNotification(user, file);
} catch {
Logger.info(`The file ${getFileName(file)} was deleted`);

return NextResponse.json(
{
message:
"An error occured when removing this file, please contact an admin",
message: "Successfully deleted",
},
{ status: 500 }
{ status: 200 }
);
}

Logger.info(`The file ${getFileName(file)} was deleted`);

return NextResponse.json(
{
message: "Successfully deleted",
},
{ status: 200 }
);
});
}
68 changes: 31 additions & 37 deletions src/app/api/user/files/[page]/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { authError } from "@/lib/api-commons";
import { auth } from "@/lib/auth";
import { handleApiRequestWithUser } from "@/lib/api-commons";
import { getUserFiles, getUserFilesCount } from "@/lib/helpers/user";
import { Pagination } from "@/lib/pagination";
import { UserFilesSort } from "@/type/user/user-file-sort";
import { headers } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

const ITEMS_PER_PAGE = 15;
Expand All @@ -16,39 +14,35 @@ export async function GET(
params: Promise<{ page: string }>;
}
): Promise<NextResponse | Response> {
const { page } = await params;
const session = await auth.api.getSession({
headers: await headers(),
return handleApiRequestWithUser(async (user) => {
const { page } = await params;

const searchParams = request.nextUrl.searchParams;
const sort = {
key: searchParams.get("sortKey") ?? "createdAt",
direction: searchParams.get("sortDirection") ?? "desc",
} as UserFilesSort;

// todo: validate the sort query

const totalFiles = await getUserFilesCount(user.id);
const pagination = new Pagination();
pagination.setItemsPerPage(ITEMS_PER_PAGE);
pagination.setTotalItems(totalFiles);

const paginatedPage = await pagination.getPage(
Number(page),
async (fetchItems) => {
const files = await getUserFiles(user.id, {
limit: ITEMS_PER_PAGE,
offset: fetchItems.start,
sort: sort,
});

return files;
}
);

return NextResponse.json(paginatedPage, { status: 200 });
});
if (!session) {
return authError;
}

const searchParams = request.nextUrl.searchParams;
const sort = {
key: searchParams.get("sortKey") ?? "createdAt",
direction: searchParams.get("sortDirection") ?? "desc",
} as UserFilesSort;

// todo: validate the sort query

const totalFiles = await getUserFilesCount(session.user.id);
const pagination = new Pagination();
pagination.setItemsPerPage(ITEMS_PER_PAGE);
pagination.setTotalItems(totalFiles);

const paginatedPage = await pagination.getPage(
Number(page),
async fetchItems => {
const files = await getUserFiles(session.user.id, {
limit: ITEMS_PER_PAGE,
offset: fetchItems.start,
sort: sort,
});

return files;
}
);

return NextResponse.json(paginatedPage, { status: 200 });
}
57 changes: 23 additions & 34 deletions src/app/api/user/reset-upload-token/route.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,34 @@
import { authError } from "@/lib/api-commons";
import { handleApiRequestWithUser } from "@/lib/api-commons";
import { auth } from "@/lib/auth";
import { UserType } from "@/lib/db/schemas/auth-schema";
import { generateUploadToken } from "@/lib/helpers/user";
import Logger from "@/lib/logger";
import { Notifications } from "@/lib/notification";
import { getUserPreferences } from "@/lib/preference";
import { ApiErrorResponse, ApiSuccessResponse } from "@/type/api/responses";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";

export async function POST(
request: Request
): Promise<NextResponse<ApiSuccessResponse | ApiErrorResponse>> {
const requestHeaders = await headers();
const session = await auth.api.getSession({
headers: requestHeaders,
});
if (!session) {
return authError;
}
const user = {
...session.user,
preferences: await getUserPreferences(session.user.id),
} as UserType;
export async function POST(request: NextRequest): Promise<NextResponse> {
return handleApiRequestWithUser(async (user) => {
const requestHeaders = await headers();
try {
await auth.api.updateUser({
body: {
uploadToken: generateUploadToken(),
},
headers: requestHeaders,
});

try {
await auth.api.updateUser({
body: {
uploadToken: generateUploadToken(),
},
headers: requestHeaders,
});
Notifications.sendResetUploadTokenNotification(user);
} catch {
return NextResponse.json(
{ message: "An error occured when resetting the upload token" },
{ status: 500 }
);
}

Notifications.sendResetUploadTokenNotification(user);
} catch {
Logger.info(`User ${user.username} reset their upload token`);
return NextResponse.json(
{ message: "An error occured when resetting the upload token" },
{ status: 500 }
{ message: "Reset Upload Token" },
{ status: 200 }
);
}

Logger.info(`User ${session.user.username} reset their upload token`);
return NextResponse.json({ message: "Reset Upload Token" }, { status: 200 });
});
}
Loading

0 comments on commit 1b02c75

Please sign in to comment.