BackendUserInfo.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { pipe } from "fp-ts/function"
  2. import * as E from "fp-ts/Either"
  3. import { BehaviorSubject } from "rxjs"
  4. import { authIdToken$ } from "../fb/auth"
  5. import { runGQLQuery } from "../backend/GQLClient"
  6. import { GetUserInfoDocument } from "../backend/graphql"
  7. /*
  8. * This file deals with interfacing data provided by the
  9. * Hoppscotch Backend server
  10. */
  11. /**
  12. * Defines the information provided about a user
  13. */
  14. export interface UserInfo {
  15. /**
  16. * UID of the user
  17. */
  18. uid: string
  19. /**
  20. * Displayable name of the user (or null if none available)
  21. */
  22. displayName: string | null
  23. /**
  24. * Email of the user (or null if none available)
  25. */
  26. email: string | null
  27. /**
  28. * URL to the profile photo of the user (or null if none available)
  29. */
  30. photoURL: string | null
  31. }
  32. /**
  33. * An observable subject onto the currently logged in user info (is null if not logged in)
  34. */
  35. export const currentUserInfo$ = new BehaviorSubject<UserInfo | null>(null)
  36. /**
  37. * Initializes the currenUserInfo$ view and sets up its update mechanism
  38. */
  39. export function initUserInfo() {
  40. authIdToken$.subscribe((token) => {
  41. if (token) {
  42. updateUserInfo()
  43. } else {
  44. currentUserInfo$.next(null)
  45. }
  46. })
  47. }
  48. /**
  49. * Runs the actual user info fetching
  50. */
  51. async function updateUserInfo() {
  52. const result = await runGQLQuery({
  53. query: GetUserInfoDocument,
  54. })
  55. currentUserInfo$.next(
  56. pipe(
  57. result,
  58. E.matchW(
  59. () => null,
  60. (x) => ({
  61. uid: x.me.uid,
  62. displayName: x.me.displayName ?? null,
  63. email: x.me.email ?? null,
  64. photoURL: x.me.photoURL ?? null,
  65. })
  66. )
  67. )
  68. )
  69. }