Skip to main content

nil_ffi/
response.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use crate::request::RequestId;
5use crate::status::Status;
6use serde::Serialize;
7use std::fmt::Display;
8
9#[derive(Debug, Serialize)]
10#[serde(rename_all = "camelCase")]
11#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
12#[cfg_attr(feature = "typescript", ts(export))]
13#[cfg_attr(feature = "typescript", ts(rename = "ffi_Response"))]
14#[cfg_attr(feature = "typescript", ts(concrete(T = serde_json::Value)))]
15pub struct Response<T>
16where
17  T: Serialize,
18{
19  pub id: RequestId,
20  #[serde(flatten)]
21  pub result: Result<T>,
22}
23
24#[derive(Debug, Serialize)]
25#[serde(tag = "kind", rename_all = "kebab-case")]
26#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
27#[cfg_attr(feature = "typescript", ts(export))]
28#[cfg_attr(feature = "typescript", ts(rename = "ffi_Result"))]
29#[cfg_attr(feature = "typescript", ts(concrete(T = serde_json::Value)))]
30pub enum Result<T: Serialize> {
31  Ok { data: T },
32  Err { status: Status, error: String },
33}
34
35impl<T: Serialize> Result<T> {
36  pub(crate) fn ok(data: T) -> Self {
37    Self::Ok { data }
38  }
39
40  pub(crate) fn err<E>(error: E) -> Self
41  where
42    E: Display,
43  {
44    Self::err_with_status(error, Status::ERR_UNKNOWN)
45  }
46
47  pub(crate) fn err_with_status<E>(error: E, status: Status) -> Self
48  where
49    E: Display,
50  {
51    Self::Err { status, error: error.to_string() }
52  }
53}
54
55impl<T, E> From<std::result::Result<T, E>> for Result<T>
56where
57  T: Serialize,
58  E: Display,
59{
60  fn from(value: std::result::Result<T, E>) -> Self {
61    match value {
62      Ok(data) => Self::ok(data),
63      Err(error) => Self::err(error),
64    }
65  }
66}