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