Skip to main content

cloudillo_ref/
service.rs

1//! Internal service functions for ref management
2
3use crate::prelude::*;
4use cloudillo_types::meta_adapter::CreateRefOptions;
5use cloudillo_types::utils;
6
7/// Parameters for creating a ref internally
8pub struct CreateRefInternalParams<'a> {
9	/// The id_tag for constructing the URL
10	pub id_tag: &'a str,
11	/// Type of reference (e.g., "welcome", "email-verify")
12	pub typ: &'a str,
13	/// Optional human-readable description
14	pub description: Option<&'a str>,
15	/// Optional expiration timestamp
16	pub expires_at: Option<Timestamp>,
17	/// URL path prefix (e.g., "/onboarding/welcome")
18	pub path_prefix: &'a str,
19	/// Optional resource identifier to store with the ref
20	pub resource_id: Option<&'a str>,
21	/// Number of uses allowed (default: 1)
22	pub count: Option<u32>,
23}
24
25/// Internal API function to create a ref programmatically
26///
27/// This is a helper function for internal use (not an HTTP endpoint).
28/// It creates a ref with the given parameters and returns the ref_id and full URL.
29///
30/// # Arguments
31/// * `app` - Application state
32/// * `tn_id` - Tenant ID
33/// * `params` - Parameters for creating the reference
34///
35/// # Returns
36/// * `ref_id` - The generated reference ID
37/// * `url` - The complete URL for the reference
38pub async fn create_ref_internal(
39	app: &App,
40	tn_id: TnId,
41	params: CreateRefInternalParams<'_>,
42) -> ClResult<(String, String)> {
43	// Generate random ref_id
44	let ref_id = utils::random_id()?;
45
46	// Create ref options
47	let ref_opts = CreateRefOptions {
48		typ: params.typ.to_string(),
49		description: params.description.map(ToString::to_string),
50		expires_at: params.expires_at,
51		count: Some(params.count.unwrap_or(1)),
52		resource_id: params.resource_id.map(ToString::to_string),
53		access_level: None,
54	};
55
56	// Store the reference in database
57	app.meta_adapter.create_ref(tn_id, &ref_id, &ref_opts).await.map_err(|e| {
58		warn!(
59			error = %e,
60			tn_id = ?tn_id,
61			ref_id = %ref_id,
62			typ = %params.typ,
63			"Failed to create reference"
64		);
65		e
66	})?;
67
68	// Construct the full URL
69	let url = format!("https://{}{}/{}", params.id_tag, params.path_prefix, ref_id);
70
71	info!(
72		tn_id = ?tn_id,
73		ref_id = %ref_id,
74		typ = %params.typ,
75		url = %url,
76		"Created reference successfully"
77	);
78
79	Ok((ref_id, url))
80}
81
82// vim: ts=4