Working on the API route for upload and the ping. adding types for actions.

This commit is contained in:
charles-gauthereau
2024-11-29 20:04:32 +01:00
parent e49a953852
commit bf4fce3a96
18 changed files with 283 additions and 30 deletions
+2
View File
@@ -38,4 +38,6 @@ next-env.d.ts
public/uploads/* public/uploads/*
!public/uploads/ !public/uploads/
private/uploads/*
/.env /.env
@@ -11,6 +11,7 @@ import {GearIcon} from "@radix-ui/react-icons";
import Link from "next/link"; import Link from "next/link";
import {AgentModalKey} from "@/components/wrappers/Agent/AgentModalKey/AgentModalKey"; import {AgentModalKey} from "@/components/wrappers/Agent/AgentModalKey/AgentModalKey";
import {KeyRound} from "lucide-react"; import {KeyRound} from "lucide-react";
import {BackupButton} from "@/components/wrappers/BackupButton/BackupButton";
export default async function RoutePage(props: PageParams<{ agentId: string }>) { export default async function RoutePage(props: PageParams<{ agentId: string }>) {
@@ -76,7 +77,6 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null
return ( return (
<Page> <Page>
<div className="justify-between gap-2 sm:flex"> <div className="justify-between gap-2 sm:flex">
@@ -93,7 +93,7 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
</AgentModalKey> </AgentModalKey>
</PageTitle> </PageTitle>
<PageActions className="justify-between"> <PageActions className="justify-between">
<Button>Backup</Button> <BackupButton/>
<Button>Restore</Button> <Button>Restore</Button>
</PageActions> </PageActions>
</div> </div>
@@ -0,0 +1,2 @@
+127
View File
@@ -0,0 +1,127 @@
import {NextResponse} from "next/server";
import {Body} from "../status/route";
import {prisma} from "@/prisma";
import {isUuidv4} from "@/utils/verify-uuid";
import {uploadLocalPrivate} from "@/features/upload/private/upload.action";
import {v4 as uuidv4} from "uuid";
export async function POST(
request: Request,
{params}: { params: Promise<{ agentId: string }> }
) {
try {
const contentType = request.headers.get("Content-Type");
// Ensure `contentType` is not null before checking
if (!contentType || (!contentType.includes("multipart/form-data"))) {
return NextResponse.json(
{ error: 'Unsupported or missing Content-Type' },
{ status: 400 }
);
}
const agentId = (await params).agentId
const formData = await request.formData();
const generatedId = formData.get("generatedId") as string;
if (!isUuidv4(generatedId)) {
return NextResponse.json(
{error: "generatedId is not a valid uuid"},
{status: 500}
);
}
const agent = await prisma.agent.findFirst({
where: {
id: agentId
}
})
if (!agent) {
return NextResponse.json({error: "Agent not found"}, {status: 404})
}
const database = await prisma.database.findFirst({
where: {
generatedId: generatedId
}
})
if (!database) {
return NextResponse.json({error: "Database associated with generatedId provided not found"}, {status: 404})
}
const backup = await prisma.backup.findFirst({
where: {
status : "ongoing",
databaseId: database.id
}
})
if (!backup) {
return NextResponse.json({error: "Unable to fin the corresponding backup"}, {status: 404})
}
const status = formData.get("status") as string;
if(status === "success"){
const file = formData.get("file") as File
const uuid = uuidv4()
const fileName = `${uuid}.dump`
const buffer = Buffer.from(await file.arrayBuffer());
const {success, message, filePath} = await uploadLocalPrivate(fileName, buffer)
if (!success){
return NextResponse.json(
{error: message},
{status: 500}
);
}
await prisma.backup.update({
where: {
id : backup.id,
},
data: {
file: fileName,
status: "success"
}
})
const response = {
message: true,
details: "Backup successfully uploaded"
}
return Response.json(response)
}else{
await prisma.backup.update({
where: {
id : backup.id,
},
data: {
status: "failed"
}
})
const response = {
message: true,
details: "Backup successfully updated with status failed"
}
return Response.json(response)
}
} catch (error) {
console.error('Error in POST handler:', error);
return NextResponse.json(
{error: 'Internal server error'},
{status: 500}
);
}
}
+27 -13
View File
@@ -2,18 +2,10 @@ import {Agent, Database} from "@prisma/client";
import {prisma} from "@/prisma"; import {prisma} from "@/prisma";
import {NextResponse} from "next/server"; import {NextResponse} from "next/server";
import {Body} from "./route"; import {Body} from "./route";
import {isUuidv4} from "@/utils/verify-uuid";
// Regular expression for UUIDv4
const uuidv4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// Type guard to check if a string is a valid UUIDv4
function isUuidv4(value: string): value is string {
console.log(value)
console.log(uuidv4Regex.test(value))
return uuidv4Regex.test(value);
}
@@ -22,12 +14,12 @@ function isUuidv4(value: string): value is string {
export async function handleDatabases(body: Body, agent: Agent, lastContact: Date) { export async function handleDatabases(body: Body, agent: Agent, lastContact: Date) {
const databasesResponse = []; const databasesResponse = [];
const formatDatabase = (database: Database) => ({ const formatDatabase = (database: Database, backupAction: boolean) => ({
generatedId: database.generatedId, generatedId: database.generatedId,
dbms: database.dbms, dbms: database.dbms,
data: { data: {
backup: { backup: {
action: true, action: backupAction,
cron: "", cron: "",
}, },
restore: { restore: {
@@ -44,6 +36,8 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
}, },
}); });
let backupAction: boolean = false
if (!existingDatabase) { if (!existingDatabase) {
if (!isUuidv4(db.generatedId)) { if (!isUuidv4(db.generatedId)) {
return NextResponse.json( return NextResponse.json(
@@ -62,7 +56,7 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
}); });
if (databaseCreated) { if (databaseCreated) {
databasesResponse.push(formatDatabase(databaseCreated)); databasesResponse.push(formatDatabase(databaseCreated, backupAction));
} }
} else { } else {
const databaseUpdated = await prisma.database.update({ const databaseUpdated = await prisma.database.update({
@@ -73,7 +67,27 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
lastContact: lastContact, lastContact: lastContact,
}, },
}); });
databasesResponse.push(formatDatabase(databaseUpdated));
const backup = await prisma.backup.findFirst({
where: {
databaseId: databaseUpdated.id,
status: "waiting"
}
})
if(backup){
backupAction = true
await prisma.backup.update({
where:{
id: backup.id
},
data: {
status: "ongoing"
}
})
}
databasesResponse.push(formatDatabase(databaseUpdated, backupAction));
} }
} }
return databasesResponse; return databasesResponse;
+1
View File
@@ -49,6 +49,7 @@ export async function POST(
}, },
databases: databasesResponse databases: databasesResponse
} }
console.log(response)
return Response.json(response) return Response.json(response)
} catch (error) { } catch (error) {
+2
View File
@@ -56,3 +56,5 @@ export async function GET(
}, },
}); });
} }
+1
View File
@@ -38,6 +38,7 @@ function checkRouteExists(pathname) {
// /^\/api\/auth\/\w+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123) // /^\/api\/auth\/\w+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123)
// /^\/api\/agent\/healthcheck\/\w+$/, // Dynamic route with an alphanumeric parameter (e.g., /api/user/username) // /^\/api\/agent\/healthcheck\/\w+$/, // Dynamic route with an alphanumeric parameter (e.g., /api/user/username)
/^\/api\/agent\/[^/]+\/status\/?$/, // Dynamic route for /api/agent/[id]/status /^\/api\/agent\/[^/]+\/status\/?$/, // Dynamic route for /api/agent/[id]/status
/^\/api\/agent\/[^/]+\/backup\/?$/, // Dynamic route for /api/agent/[id]/status
/^\/api\/files\/[^/]+\/?$/, /^\/api\/files\/[^/]+\/?$/,
]; ];
return routePatterns.some(pattern => pattern.test(pathname)); return routePatterns.some(pattern => pattern.test(pathname));
@@ -0,0 +1,9 @@
/*
Warnings:
- Added the required column `backupToRestore` to the `databases` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "databases" ADD COLUMN "backupToRestore" TEXT NOT NULL,
ADD COLUMN "isWaitingForBackup" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "databases" ALTER COLUMN "backupToRestore" DROP NOT NULL,
ALTER COLUMN "isWaitingForBackup" DROP NOT NULL;
+2
View File
@@ -104,6 +104,8 @@ model Database {
description String? description String?
backupPolicy String? @map("backup_policy") backupPolicy String? @map("backup_policy")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
isWaitingForBackup Boolean? @default(false)
backupToRestore String?
agentId String @map("agent_id") agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade) agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
@@ -0,0 +1,29 @@
"use client"
import {Button} from "@/components/ui/button";
import {useMutation} from "@tanstack/react-query";
import {backupButtonAction} from "@/components/wrappers/BackupButton/backup-button.action";
export type BackupButtonProps = {
// databaseId: string;
}
export const BackupButton = () => {
const mutation = useMutation({
mutationFn: async (databaseId: string) => {
const result = await backupButtonAction(databaseId)
console.log(result)
}
})
return (
<Button
onClick={() => {
mutation.mutateAsync("cm430tnop0001bcm0vo9b5nfx")
}}
>Backup
</Button>
)
}
@@ -0,0 +1,42 @@
"use server"
import {userAction} from "@/safe-actions";
import {z} from "zod";
import {prisma} from "@/prisma";
import {ServerActionResult} from "@/types/action-type";
import {Backup} from "@prisma/client";
export const backupButtonAction = userAction
.schema(z.string())
.action(async ({ parsedInput, ctx }): Promise<ServerActionResult<Backup>> => {
try {
const backup = await prisma.backup.create({
data: {
databaseId: parsedInput,
status: "waiting",
},
});
return {
success: true,
value: backup,
actionSuccess: {
message: "Backup has been successfully created.",
messageParams: { databaseId: parsedInput },
},
};
} catch (error) {
console.error("Error creating backup:", error);
return {
success: false,
actionError: {
message: "Failed to create backup.",
status: 500, // Optional: Use a meaningful status code
cause: error instanceof Error ? error.message : "Unknown error",
messageParams: { databaseId: parsedInput },
},
};
}
});
+13 -7
View File
@@ -6,22 +6,28 @@ import {getServerUrl} from "@/utils/get-server-url";
const privateLocalDir = "private/uploads/"; const privateLocalDir = "private/uploads/";
async function uploadLocalPrivate(fileName: string, buffer: any) {
export async function uploadLocalPrivate(fileName: string, buffer: any) {
try { try {
await mkdir(path.join(process.cwd(), privateLocalDir), { recursive: true }); await mkdir(path.join(process.cwd(), privateLocalDir), { recursive: true });
return await writeFile(
path.join(process.cwd(), privateLocalDir + fileName), await writeFile(
path.join(process.cwd(), privateLocalDir, fileName),
buffer buffer
) );
return {
success: true,
message: "File uploaded successfully",
filePath: path.join(privateLocalDir, fileName),
};
} catch (error) { } catch (error) {
console.log("Error occured ", error); console.error("Error occurred:", error);
throw new Error('An error occured while importing private file'); throw new Error("An error occurred while importing the private file");
} }
} }
export async function getFileUrlPresignedLocal(fileName: string) { export async function getFileUrlPresignedLocal(fileName: string) {
try { try {
const filePath = path.join(privateLocalDir, fileName); const filePath = path.join(privateLocalDir, fileName);
+1
View File
@@ -1,3 +1,4 @@
import {createSafeActionClient} from "next-safe-action"; import {createSafeActionClient} from "next-safe-action";
import {currentUser} from "@/auth/current-user"; import {currentUser} from "@/auth/current-user";
+6
View File
@@ -0,0 +1,6 @@
export type ServerActionResult<T> = { success: true; value: T; actionSuccess?: ActionSuccessMessage } | { success: false; actionError: ActionErrorMessage };
export type ActionErrorMessage = { message?: string; status?: number; cause?: string; messageParams?: Record<string, string | number> };
export type ActionSuccessMessage = { message?: string; messageParams?: Record<string, string | number> };
+6
View File
@@ -0,0 +1,6 @@
const uuidv4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function isUuidv4(value: string): value is string {
return uuidv4Regex.test(value);
}