1use crate::MsgPackExtractorFuture;
2
3use super::{MsgPackConfig, MsgPackError, MsgPackMessage, DEFAULT_CONFIG};
4use actix_web::{
5 body::BoxBody, dev::Payload, error::Error, FromRequest, HttpRequest, HttpResponse, Responder,
6};
7use mime::APPLICATION_MSGPACK;
8use serde::{de::DeserializeOwned, Serialize};
9use std::{
10 fmt,
11 ops::{Deref, DerefMut},
12};
13
14pub struct MsgPack<T>(pub T);
15
16impl<T> Deref for MsgPack<T> {
17 type Target = T;
18
19 fn deref(&self) -> &T {
20 &self.0
21 }
22}
23
24impl<T> DerefMut for MsgPack<T> {
25 fn deref_mut(&mut self) -> &mut T {
26 &mut self.0
27 }
28}
29
30impl<T> fmt::Debug for MsgPack<T>
31where
32 T: fmt::Debug,
33{
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "MsgPack: {:?}", self.0)
36 }
37}
38
39impl<T> fmt::Display for MsgPack<T>
40where
41 T: fmt::Display,
42{
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 fmt::Display::fmt(&self.0, f)
45 }
46}
47
48impl<T: DeserializeOwned> FromRequest for MsgPack<T>
49where
50 T: 'static,
51{
52 type Error = Error;
53 type Future = MsgPackExtractorFuture<T>;
54
55 #[inline]
56 fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
57 let config = req.app_data::<MsgPackConfig>().unwrap_or(&DEFAULT_CONFIG);
58 let limit = config.limit;
59 let err_handler = config.error_handler.clone();
60 let content_type = config.content_type.clone();
61
62 MsgPackExtractorFuture {
63 req: req.clone(),
64 fut: MsgPackMessage::new(req, payload, content_type).limit(limit),
65 err_handler,
66 }
67 }
68}
69
70impl<T: Serialize> Responder for MsgPack<T> {
71 type Body = BoxBody;
72
73 fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
74 match rmp_serde::to_vec_named(&self.0) {
75 Ok(body) => {
76 match HttpResponse::Ok().content_type(APPLICATION_MSGPACK).message_body(body) {
77 Ok(response) => response.map_into_boxed_body(),
78 Err(err) => HttpResponse::from_error(err),
79 }
80 },
81 Err(err) => HttpResponse::from_error(MsgPackError::Serialize(err)),
82 }
83 }
84}