I need a route to handle webhook events coming to an Axum API.
The Json body has an event
property giving the event name, and a data
property which will be a different object based on the event
type.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DbWebhookEvent {
SignUpCompleted,
}
#[derive(Debug, Deserialize)]
pub struct DbWebhookBody {
event: DbWebhookEvent,
data: ??
}
I looked at using the serde RawValue for this use-case but when I add a lifetime to the DbWebhookBody
struct I am not sure how this should bubble up through to the app router.
I will then need to deserialize data
once the event type is known so that it can be acted upon. My handler function is currently like this:
pub async fn post_db_webhook(
Extension(app_state): Extension<Arc<AppState>>,
Json(body): Json<DbWebhookBody>,
) -> Result<Json<DbWebhookResponse>> {
match body.event {
DbWebhookEvent::SignUpCompleted => {
// need to deserialize body data to a struct
let signup_data = SignupData::from(body.data)
signup_completed(app_state, body.data);
}
}
Ok(Json(DbWebhookResponse { ok: true }))
}