in-app-notification.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import type { SWRConfiguration, SWRResponse } from 'swr';
  2. import useSWR from 'swr';
  3. import { SupportedTargetModel } from '~/interfaces/activity';
  4. import type {
  5. IInAppNotification,
  6. InAppNotificationStatuses,
  7. PaginateResult,
  8. } from '~/interfaces/in-app-notification';
  9. import * as userSerializers from '~/models/serializers/in-app-notification-snapshot/user';
  10. import loggerFactory from '~/utils/logger';
  11. import { apiv3Get } from '../client/util/apiv3-client';
  12. const logger = loggerFactory('growi:cli:InAppNotification');
  13. type inAppNotificationPaginateResult = PaginateResult<IInAppNotification>;
  14. export const useSWRxInAppNotifications = (
  15. limit: number,
  16. offset?: number,
  17. status?: InAppNotificationStatuses,
  18. config?: SWRConfiguration,
  19. ): SWRResponse<PaginateResult<IInAppNotification>, Error> => {
  20. return useSWR(
  21. ['/in-app-notification/list', limit, offset, status],
  22. ([endpoint]) =>
  23. apiv3Get(endpoint, { limit, offset, status }).then((response) => {
  24. const inAppNotificationPaginateResult =
  25. response.data as inAppNotificationPaginateResult;
  26. inAppNotificationPaginateResult.docs.forEach((doc) => {
  27. try {
  28. if (doc.targetModel === SupportedTargetModel.MODEL_USER) {
  29. doc.parsedSnapshot = userSerializers.parseSnapshot(doc.snapshot);
  30. }
  31. } catch (err) {
  32. logger.warn('Failed to parse snapshot', err);
  33. }
  34. });
  35. return inAppNotificationPaginateResult;
  36. }),
  37. config,
  38. );
  39. };
  40. export const useSWRxInAppNotificationStatus = (): SWRResponse<
  41. number,
  42. Error
  43. > => {
  44. return useSWR('/in-app-notification/status', (endpoint) =>
  45. apiv3Get(endpoint).then((response) => response.data.count),
  46. );
  47. };