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