Files
formbricks/apps/web/app/api/v1/webhooks/route.ts
T
pandeymangg a5a036ae05 fixes
2026-03-10 19:45:56 +05:30

93 lines
2.8 KiB
TypeScript

import { DatabaseError, InvalidInputError } from "@formbricks/types/errors";
import { createWebhook, getWebhooks } from "@/app/api/v1/webhooks/lib/webhook";
import { ZWebhookInput } from "@/app/api/v1/webhooks/types/webhooks";
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { hasPermission } from "@/modules/organization/settings/api-keys/lib/utils";
export const GET = withV1ApiWrapper({
handler: async ({ authentication }: THandlerParams) => {
if (!authentication || !("apiKeyId" in authentication)) {
return { response: responses.notAuthenticatedResponse() };
}
try {
const environmentIds = authentication.environmentPermissions.map(
(permission) => permission.environmentId
);
const webhooks = await getWebhooks(environmentIds);
return {
response: responses.successResponse(webhooks),
};
} catch (error) {
if (error instanceof DatabaseError) {
return {
response: responses.internalServerErrorResponse(error.message),
};
}
throw error;
}
},
});
export const POST = withV1ApiWrapper({
handler: async ({ req, auditLog, authentication }: THandlerParams) => {
if (!authentication || !("apiKeyId" in authentication)) {
return { response: responses.notAuthenticatedResponse() };
}
const webhookInput = await req.json();
const inputValidation = ZWebhookInput.safeParse(webhookInput);
if (!inputValidation.success) {
return {
response: responses.badRequestResponse(
"Fields are missing or incorrectly formatted",
transformErrorToDetails(inputValidation.error),
true
),
};
}
const environmentId = inputValidation.data.environmentId;
if (!environmentId) {
return {
response: responses.badRequestResponse("Environment ID is required"),
};
}
if (!hasPermission(authentication.environmentPermissions, environmentId, "POST")) {
return {
response: responses.unauthorizedResponse(),
};
}
try {
const webhook = await createWebhook(inputValidation.data);
if (auditLog) {
auditLog.targetId = webhook.id;
auditLog.newObject = webhook;
}
return {
response: responses.successResponse(webhook),
};
} catch (error) {
if (error instanceof InvalidInputError) {
return {
response: responses.badRequestResponse(error.message),
};
}
if (error instanceof DatabaseError) {
return {
response: responses.internalServerErrorResponse(error.message),
};
}
throw error;
}
},
action: "created",
targetType: "webhook",
});