From cbf5e948db5237c0efc359fac19e116ec4c1d561 Mon Sep 17 00:00:00 2001 From: Wyatt Herkamp Date: Sun, 27 Aug 2023 18:47:05 -0400 Subject: [PATCH] Implement Deserialize and Default for actix_web::Data (#3109) * Implement Default and Deserialize for Data * FMT * Change Log * tweak changelog * chore: whitespace --------- Co-authored-by: Rob Ede --- actix-web/CHANGES.md | 2 ++ actix-web/src/data.rs | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/actix-web/CHANGES.md b/actix-web/CHANGES.md index 518a0250..97bf4ed0 100644 --- a/actix-web/CHANGES.md +++ b/actix-web/CHANGES.md @@ -9,6 +9,8 @@ - Add `web::Payload::to_bytes[_limited]()` helper methods. - Add missing constructors on `HttpResponse` for several status codes. - Add `http::header::ContentLength` typed header. +- Implement `Default` for `web::Data`. +- Implement `serde::Deserialize` for `web::Data`. ### Changed diff --git a/actix-web/src/data.rs b/actix-web/src/data.rs index 423dd598..449a24a6 100644 --- a/actix-web/src/data.rs +++ b/actix-web/src/data.rs @@ -3,7 +3,7 @@ use std::{any::type_name, ops::Deref, sync::Arc}; use actix_http::Extensions; use actix_utils::future::{err, ok, Ready}; use futures_core::future::LocalBoxFuture; -use serde::Serialize; +use serde::{de, Serialize}; use crate::{dev::Payload, error, Error, FromRequest, HttpRequest}; @@ -128,6 +128,12 @@ impl From> for Data { } } +impl Default for Data { + fn default() -> Self { + Data::new(T::default()) + } +} + impl Serialize for Data where T: Serialize, @@ -139,6 +145,17 @@ where self.0.serialize(serializer) } } +impl<'de, T> de::Deserialize<'de> for Data +where + T: de::Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: de::Deserializer<'de>, + { + Ok(Data::new(T::deserialize(deserializer)?)) + } +} impl FromRequest for Data { type Error = Error;