This event is triggered whenever a user removes a connection. The registered handler runs before the connection is deleted, meaning that if the handler throws an error, the connection will not be removed. You can use the handler to perform any necessary teardown work.

Example

Here’s an example that cleans up a webhook handler.

TypeScript
// src/events/connection-removed.event.ts
import {listWebhookHandlers, deleteWebhookHandler} from "attio/server"
import type {Connection} from "attio/server"

export default async function connectionRemoved({connection}: {connection: Connection}) {
    const webhookHandlers = await listWebhookHandlers()
    const userWebhookHandlers = webhookHandlers.filter(
        (webhookHandler) =>
            webhookHandler.fileName === "acme-webhook" &&
            webhookHandler.createdBy.id === connection.createdBy.id
    )

    for (const webhookHandler of userWebhookHandlers) {
        const acmeResponse = await fetch(
            `https://api.acmeinc.com/api/v1/webhooks${webhookHandler.externalWebhookId}`,
            {
                method: "DELETE",
                headers: {
                    Authorization: `Bearer ${connection.value}`,
                },
            }
        )

        if (!acmeResponse.ok) {
            throw new Error("Failed to register webhook")
        }

        // We store the external webhook ID in Attio so we can delete it later
        await deleteWebhookHandler(webhookHandler.id)
    }
}