BackendUserInfo.ts 1.6 KB

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