fosrl.pangolin/server/routers/client/deleteClient.ts

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-02-21 14:39:10 -05:00
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { clients, clientSites } from "@server/db";
2025-02-21 14:39:10 -05:00
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
2025-04-20 17:00:45 -04:00
import { OpenAPITags, registry } from "@server/openApi";
2025-02-21 14:39:10 -05:00
const deleteClientSchema = z
.object({
2025-02-21 15:26:48 -05:00
clientId: z.string().transform(Number).pipe(z.number().int().positive())
2025-02-21 14:39:10 -05:00
})
.strict();
2025-04-20 17:00:45 -04:00
registry.registerPath({
method: "delete",
path: "/client/{clientId}",
description: "Delete a client by its client ID.",
tags: [OpenAPITags.Client],
request: {
params: deleteClientSchema
},
responses: {}
});
2025-02-21 15:26:48 -05:00
export async function deleteClient(
2025-02-21 14:39:10 -05:00
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = deleteClientSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
2025-02-21 15:26:48 -05:00
const { clientId } = parsedParams.data;
2025-02-21 14:39:10 -05:00
2025-02-21 15:26:48 -05:00
const [client] = await db
2025-02-21 14:39:10 -05:00
.select()
2025-02-21 15:26:48 -05:00
.from(clients)
.where(eq(clients.clientId, clientId))
2025-02-21 14:39:10 -05:00
.limit(1);
2025-02-21 15:26:48 -05:00
if (!client) {
2025-02-21 14:39:10 -05:00
return next(
createHttpError(
HttpCode.NOT_FOUND,
2025-02-21 18:51:27 -05:00
`Client with ID ${clientId} not found`
2025-02-21 14:39:10 -05:00
)
);
}
await db.transaction(async (trx) => {
// Delete the client-site associations first
await trx
.delete(clientSites)
.where(eq(clientSites.clientId, clientId));
// Then delete the client itself
await trx
.delete(clients)
.where(eq(clients.clientId, clientId));
});
2025-02-21 14:39:10 -05:00
return response(res, {
data: null,
success: true,
error: false,
2025-02-21 15:26:48 -05:00
message: "Client deleted successfully",
2025-02-21 14:39:10 -05:00
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
2025-04-20 17:00:45 -04:00
}