fhir_sdk/extensions/
any_resource.rs

1//! Traits for all resources.
2
3use fhir_model::for_all_versions;
4
5use crate::version::{FhirVersion, fhir_version};
6
7/// Basic trait to combine all resources from all FHIR versions to one.
8/// Especially for use in the client to accept and handly any resource.
9/// Only implemented if "builders" feature is active.
10pub trait AnyResource<V: FhirVersion>: Send + Sync {
11	/// ResourceType of this resource.
12	const TYPE: V::ResourceType;
13	/// Resource type of the resource as `&str`. Must be valid for use in URLs.
14	const TYPE_STR: &'static str;
15
16	/// Get the resource's ID as string.
17	fn id(&self) -> Option<&str>;
18	/// Set the resource's ID.
19	fn set_id(&mut self, id: String);
20	/// Get the resource's version ID as string.
21	fn version_id(&self) -> Option<&str>;
22	/// Set the resource's version ID.
23	fn set_version_id(&mut self, version_id: String);
24}
25
26/// Implement `AnyResource` for all fhir versions.
27macro_rules! impl_any_resource {
28	($version:ident) => {
29		use fhir_model::$version;
30
31		impl<R> AnyResource<fhir_version!($version)> for R
32		where
33			R: $version::resources::NamedResource + $version::resources::BaseResource + Send + Sync,
34		{
35			const TYPE: $version::resources::ResourceType = R::TYPE;
36			const TYPE_STR: &'static str = R::TYPE.as_str();
37
38			#[inline]
39			fn id(&self) -> Option<&str> {
40				$version::resources::BaseResource::id(self).as_deref()
41			}
42
43			#[inline]
44			fn set_id(&mut self, id: String) {
45				$version::resources::BaseResource::set_id(self, Some(id));
46			}
47
48			#[inline]
49			fn version_id(&self) -> Option<&str> {
50				self.meta().as_ref().and_then(|meta| meta.version_id.as_deref())
51			}
52
53			#[inline]
54			fn set_version_id(&mut self, version_id: String) {
55				if let Some(meta) = self.meta_mut() {
56					meta.version_id = Some(version_id);
57				} else {
58					#[allow(
59						clippy::unwrap_used,
60						reason = "Meta does not require any field and will succeed building."
61					)]
62					self.set_meta(Some(
63						$version::types::Meta::builder().version_id(version_id).build().unwrap(),
64					));
65				}
66			}
67		}
68	};
69}
70#[cfg(feature = "builders")]
71for_all_versions!(impl_any_resource);