BackendUserInfo.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * Whether the user has access to Early Access features
  31. */
  32. eaInvited: boolean
  33. }
  34. /**
  35. * An observable subject onto the currently logged in user info (is null if not logged in)
  36. */
  37. export const currentUserInfo$ = new BehaviorSubject<UserInfo | null>(null)
  38. /**
  39. * Initializes the currenUserInfo$ view and sets up its update mechanism
  40. */
  41. export function initUserInfo() {
  42. authIdToken$.subscribe((token) => {
  43. if (token) {
  44. updateUserInfo()
  45. } else {
  46. currentUserInfo$.next(null)
  47. }
  48. })
  49. }
  50. /**
  51. * Runs the actual user info fetching
  52. */
  53. async function updateUserInfo() {
  54. try {
  55. const { data } = await apolloClient.query({
  56. query: gql`
  57. query GetUserInfo {
  58. me {
  59. uid
  60. displayName
  61. email
  62. photoURL
  63. eaInvited
  64. }
  65. }
  66. `,
  67. })
  68. currentUserInfo$.next({
  69. uid: data.me.uid,
  70. displayName: data.me.displayName,
  71. email: data.me.email,
  72. photoURL: data.me.photoURL,
  73. eaInvited: data.me.eaInvited,
  74. })
  75. } catch (e) {
  76. currentUserInfo$.next(null)
  77. }
  78. }