From 756863f298f9e4277863f9e8758e253c5ae95923 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Fri, 11 Oct 2024 22:57:56 -0400 Subject: Return a distinct error when an invite username is in use. I've also aligned channel creation with this (it's 409 Conflict). To make server setup more distinct, it now returns 503 Service Unavailable if setup has not been completed. --- src/db/mod.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src/db') diff --git a/src/db/mod.rs b/src/db/mod.rs index fa3d74e..6005813 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -4,6 +4,7 @@ use std::str::FromStr; use hex_literal::hex; use sqlx::{ + error::{DatabaseError, ErrorKind}, migrate::{Migrate as _, MigrateDatabase as _}, sqlite::{Sqlite, SqliteConnectOptions, SqlitePool, SqlitePoolOptions}, }; @@ -161,3 +162,32 @@ impl NotFound for Result { self.optional()?.ok_or_else(map) } } + +pub trait Duplicate { + type Ok; + type Error; + + fn duplicate(self, map: F) -> Result + where + E: From, + F: FnOnce() -> E; +} + +impl Duplicate for Result { + type Ok = T; + type Error = sqlx::Error; + + fn duplicate(self, map: F) -> Result + where + E: From, + F: FnOnce() -> E, + { + match self { + Ok(value) => Ok(value), + Err(error) => match error.as_database_error().map(DatabaseError::kind) { + Some(ErrorKind::UniqueViolation) => Err(map()), + _ => Err(error.into()), + }, + } + } +} -- cgit v1.2.3