server_api.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. use crate::{errors::FlowyError, services::server::DocumentServerAPI};
  2. use backend_service::{configuration::*, request::HttpRequestBuilder};
  3. use flowy_collaboration::entities::doc::{CreateDocParams, DocIdentifier, DocumentInfo, ResetDocumentParams};
  4. use lib_infra::future::FutureResult;
  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) -> FutureResult<(), FlowyError> {
  13. let token = token.to_owned();
  14. let url = self.config.doc_url();
  15. FutureResult::new(async move { create_doc_request(&token, params, &url).await })
  16. }
  17. fn read_doc(&self, token: &str, params: DocIdentifier) -> FutureResult<Option<DocumentInfo>, FlowyError> {
  18. let token = token.to_owned();
  19. let url = self.config.doc_url();
  20. FutureResult::new(async move { read_doc_request(&token, params, &url).await })
  21. }
  22. fn update_doc(&self, token: &str, params: ResetDocumentParams) -> FutureResult<(), FlowyError> {
  23. let token = token.to_owned();
  24. let url = self.config.doc_url();
  25. FutureResult::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<(), FlowyError> {
  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(
  41. token: &str,
  42. params: DocIdentifier,
  43. url: &str,
  44. ) -> Result<Option<DocumentInfo>, FlowyError> {
  45. let doc = request_builder()
  46. .get(&url.to_owned())
  47. .header(HEADER_TOKEN, token)
  48. .protobuf(params)?
  49. .option_response()
  50. .await?;
  51. Ok(doc)
  52. }
  53. pub async fn update_doc_request(token: &str, params: ResetDocumentParams, url: &str) -> Result<(), FlowyError> {
  54. let _ = request_builder()
  55. .patch(&url.to_owned())
  56. .header(HEADER_TOKEN, token)
  57. .protobuf(params)?
  58. .send()
  59. .await?;
  60. Ok(())
  61. }