request.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {
  2. audit,
  3. combineLatest,
  4. distinctUntilChanged,
  5. EMPTY,
  6. from,
  7. map,
  8. Subscription,
  9. } from "rxjs"
  10. import { doc, getDoc, getFirestore, setDoc } from "firebase/firestore"
  11. import {
  12. HoppRESTRequest,
  13. translateToNewRequest,
  14. } from "../types/HoppRESTRequest"
  15. import { currentUser$, HoppUser } from "./auth"
  16. import { restRequest$ } from "~/newstore/RESTSession"
  17. /**
  18. * Writes a request to a user's firestore sync
  19. *
  20. * @param user The user to write to
  21. * @param request The request to write to the request sync
  22. */
  23. function writeCurrentRequest(user: HoppUser, request: HoppRESTRequest) {
  24. return setDoc(
  25. doc(getFirestore(), "users", user.uid, "requests", "rest"),
  26. request
  27. )
  28. }
  29. /**
  30. * Loads the synced request from the firestore sync
  31. *
  32. * @returns Fetched request object if exists else null
  33. */
  34. export async function loadRequestFromSync(): Promise<HoppRESTRequest | null> {
  35. const currentUser = currentUser$.value
  36. if (!currentUser)
  37. throw new Error("Cannot load request from sync without login")
  38. const fbDoc = await getDoc(
  39. doc(getFirestore(), "users", currentUser.uid, "requests", "rest")
  40. )
  41. const data = fbDoc.data()
  42. if (!data) return null
  43. else return translateToNewRequest(data)
  44. }
  45. /**
  46. * Performs sync of the REST Request session with Firestore.
  47. *
  48. * @returns A subscription to the sync observable stream.
  49. * Unsubscribe to stop syncing.
  50. */
  51. export function startRequestSync(): Subscription {
  52. const sub = combineLatest([
  53. currentUser$,
  54. restRequest$.pipe(distinctUntilChanged()),
  55. ])
  56. .pipe(
  57. map(([user, request]) =>
  58. user ? from(writeCurrentRequest(user, request)) : EMPTY
  59. ),
  60. audit((x) => x)
  61. )
  62. .subscribe(() => {
  63. // NOTE: This subscription should be kept
  64. })
  65. return sub
  66. }