server_api.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use crate::{errors::DocError, services::server::DocumentServerAPI};
  2. use backend_service::{configuration::*, request::HttpRequestBuilder};
  3. use flowy_document_infra::entities::doc::{CreateDocParams, Doc, DocIdentifier, UpdateDocParams};
  4. use lib_infra::future::ResultFuture;
  5. pub struct DocServer {
  6. config: ClientServerConfiguration,
  7. }
  8. impl DocServer {
  9. pub fn new(config: ClientServerConfiguration) -> Self { Self { config } }
  10. }
  11. impl DocumentServerAPI for DocServer {
  12. fn create_doc(&self, token: &str, params: CreateDocParams) -> ResultFuture<(), DocError> {
  13. let token = token.to_owned();
  14. let url = self.config.doc_url();
  15. ResultFuture::new(async move { create_doc_request(&token, params, &url).await })
  16. }
  17. fn read_doc(&self, token: &str, params: DocIdentifier) -> ResultFuture<Option<Doc>, DocError> {
  18. let token = token.to_owned();
  19. let url = self.config.doc_url();
  20. ResultFuture::new(async move { read_doc_request(&token, params, &url).await })
  21. }
  22. fn update_doc(&self, token: &str, params: UpdateDocParams) -> ResultFuture<(), DocError> {
  23. let token = token.to_owned();
  24. let url = self.config.doc_url();
  25. ResultFuture::new(async move { update_doc_request(&token, params, &url).await })
  26. }
  27. }
  28. pub(crate) fn request_builder() -> HttpRequestBuilder {
  29. HttpRequestBuilder::new().middleware(super::middleware::MIDDLEWARE.clone())
  30. }
  31. pub async fn create_doc_request(token: &str, params: CreateDocParams, url: &str) -> Result<(), DocError> {
  32. let _ = request_builder()
  33. .post(&url.to_owned())
  34. .header(HEADER_TOKEN, token)
  35. .protobuf(params)?
  36. .send()
  37. .await?;
  38. Ok(())
  39. }
  40. pub async fn read_doc_request(token: &str, params: DocIdentifier, url: &str) -> Result<Option<Doc>, DocError> {
  41. let doc = request_builder()
  42. .get(&url.to_owned())
  43. .header(HEADER_TOKEN, token)
  44. .protobuf(params)?
  45. .option_response()
  46. .await?;
  47. Ok(doc)
  48. }
  49. pub async fn update_doc_request(token: &str, params: UpdateDocParams, url: &str) -> Result<(), DocError> {
  50. let _ = request_builder()
  51. .patch(&url.to_owned())
  52. .header(HEADER_TOKEN, token)
  53. .protobuf(params)?
  54. .send()
  55. .await?;
  56. Ok(())
  57. }