1
use std::fmt::Debug;
2

            
3
use serde::{Deserialize, Serialize};
4

            
5
/// A definition of a custom API. The `Request` associated type is what a
6
/// connected client can send. The `Response` associated type is what your API
7
/// is expecetd to send from the server to the client. The `Dispatcher` is the
8
/// type that will handle the custom API requests.
9
///
10
/// This feature is powered by [`actionable`] through these derives:
11
///
12
/// * [`Action`](crate::permissions::Action) (trait and derive macro)
13
/// * [`Actionable`](crate::permissions::Actionable) (derive macro)
14
pub trait CustomApi: Debug + Send + Sync + 'static {
15
    /// The type that represents an API request. This type is what clients will send to the server.
16
    type Request: Serialize + for<'de> Deserialize<'de> + Send + Sync + Debug;
17
    /// The type that represents an API response. This type will be sent to clients from the server.
18
    type Response: Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync + Debug;
19
    /// The error type that this Api instance can return.
20
    type Error: CustomApiError;
21
}
22

            
23
impl CustomApi for () {
24
    type Request = ();
25
    type Response = ();
26
    type Error = Infallible;
27
}
28

            
29
/// An Error type that can be used in within a [`CustomApi`] definition.
30
///
31
/// The reason `std::convert::Infallible` can't be used is because `CustomApi`
32
/// errors must be able to be serialized across a network connection. While a
33
/// value will never be present when this is Infallible, the associated type
34
/// still must be declared as Serializable.
35
#[derive(thiserror::Error, Debug, Clone, Serialize, Deserialize)]
36
#[error("an unreachable error")]
37
pub enum Infallible {}
38

            
39
/// An error that can be used within a [`CustomApi`] definition.
40
pub trait CustomApiError:
41
    std::fmt::Display + Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync + Debug
42
{
43
}
44

            
45
impl<T> CustomApiError for T where
46
    T: std::fmt::Display + Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync + Debug
47
{
48
}
49

            
50
/// The result of executing a custom API call.
51
pub type CustomApiResult<Api> = Result<<Api as CustomApi>::Response, <Api as CustomApi>::Error>;