Skip to content

Commit

Permalink
twiq: Add firestore_rest::commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Aug 22, 2022
1 parent dc660d2 commit 6690512
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions twiq/crates/db/src/firestore_rest.rs
Expand Up @@ -191,6 +191,44 @@ pub async fn begin_transaction(
.await?)
}

#[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CommitRequestBody {
writes: Vec<Write>,
#[serde(skip_serializing_if = "Option::is_none")]
transaction: Option<String>,
}

#[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Write {
// TODO:
// Update {}
Delete(String),
// TODO:
// Transform {},
}

pub async fn commit(
(token, project_id): (&str, &str),
database: &str,
body: CommitRequestBody,
) -> anyhow::Result<Response> {
// <https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents/commit>
let method = Method::POST;
let url = format!(
"https://firestore.googleapis.com/v1/{}/documents:commit",
database
);
Ok(Client::new()
.request(method, url)
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json")
.header("X-Goog-User-Project", project_id)
.body(serde_json::to_string(&body)?)
.send()
.await?)
}

pub async fn create_document(
(token, project_id): (&str, &str),
parent: &str,
Expand Down Expand Up @@ -470,4 +508,32 @@ mod tests {
);
Ok(())
}

#[test]
fn commit_request_body_test() -> anyhow::Result<()> {
assert_eq!(
serde_json::to_string(&CommitRequestBody {
writes: vec![Write::Delete("123".to_owned())],
transaction: None
})?,
r#"{"writes":[{"delete":"123"}]}"#
);
assert_eq!(
serde_json::to_string(&CommitRequestBody {
writes: vec![Write::Delete("123".to_owned())],
transaction: Some("456".to_owned())
})?,
r#"{"writes":[{"delete":"123"}],"transaction":"456"}"#
);
Ok(())
}

#[test]
fn write_test() -> anyhow::Result<()> {
assert_eq!(
serde_json::to_string(&Write::Delete("123".to_owned()))?,
r#"{"delete":"123"}"#
);
Ok(())
}
}

0 comments on commit 6690512

Please sign in to comment.