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