use crate::client::{AuraClient, RequestBody};
use crate::error::AuraError;
use crate::types::{AuraResponse, CronJob, FunctionDef, Job};
pub struct FunctionsService {
client: AuraClient,
}
#[derive(Debug, Clone, Default)]
pub struct InvokeOptions {
pub body: Option<serde_json::Value>,
pub method: Option<String>,
pub path: Option<String>,
pub headers: Option<std::collections::HashMap<String, String>>,
}
impl FunctionsService {
pub fn new(client: AuraClient) -> Self {
Self { client }
}
fn prefix(&self) -> String {
"/v1/functions".to_string()
}
pub async fn invoke<T>(
&self,
slug: &str,
options: Option<InvokeOptions>,
) -> Result<AuraResponse<T>, AuraError>
where
T: serde::de::DeserializeOwned,
{
let opts = options.unwrap_or_default();
let body_payload = serde_json::json!({
"method": opts.method,
"path": opts.path,
"headers": opts.headers,
"body": opts.body,
});
self.client
.request(
reqwest::Method::POST,
&format!("{}/{}/invoke", self.prefix(), slug),
RequestBody::Json(body_payload),
)
.await
}
pub async fn list(&self) -> Result<AuraResponse<Vec<FunctionDef>>, AuraError> {
self.client
.request(reqwest::Method::GET, &self.prefix(), RequestBody::None)
.await
}
pub async fn get(&self, id: &str) -> Result<AuraResponse<FunctionDef>, AuraError> {
self.client
.request(
reqwest::Method::GET,
&format!("{}/{}", self.prefix(), id),
RequestBody::None,
)
.await
}
pub async fn list_jobs(
&self,
status: Option<&str>,
limit: Option<u32>,
) -> Result<AuraResponse<Vec<Job>>, AuraError> {
let mut query = Vec::new();
if let Some(s) = status {
query.push(format!("status={}", s));
}
if let Some(l) = limit {
query.push(format!("limit={}", l));
}
let qs = if query.is_empty() {
"".to_string()
} else {
format!("?{}", query.join("&"))
};
self.client
.request(
reqwest::Method::GET,
&format!("{}/jobs{}", self.prefix(), qs),
RequestBody::None,
)
.await
}
pub async fn get_job(&self, job_id: &str) -> Result<AuraResponse<Job>, AuraError> {
self.client
.request(
reqwest::Method::GET,
&format!("{}/jobs/{}", self.prefix(), job_id),
RequestBody::None,
)
.await
}
pub async fn list_cron_jobs(&self) -> Result<AuraResponse<Vec<CronJob>>, AuraError> {
self.client
.request(
reqwest::Method::GET,
&format!("{}/cron", self.prefix()),
RequestBody::None,
)
.await
}
pub async fn create_cron_job(
&self,
name: &str,
schedule: &str,
function_name: &str,
payload: Option<serde_json::Value>,
) -> Result<AuraResponse<CronJob>, AuraError> {
let body = serde_json::json!({
"name": name,
"schedule": schedule,
"function_name": function_name,
"payload": payload,
});
self.client
.request(
reqwest::Method::POST,
&format!("{}/cron", self.prefix()),
RequestBody::Json(body),
)
.await
}
pub async fn delete_cron_job(
&self,
name: &str,
) -> Result<AuraResponse<serde_json::Value>, AuraError> {
self.client
.request(
reqwest::Method::DELETE,
&format!("{}/cron/{}", self.prefix(), name),
RequestBody::None,
)
.await
}
}