index.ts 1.47 KB
import { getThunkActionCreator } from 'redux-thunk-routine';
import { plainToClass } from 'class-transformer';
import { fetchThreadContents as fetchThreadContentsRoutine, postThreadContent as postThreadContentRoutine } from './routines';
import AlertifyHelper from '../../../../helpers/AlertifyHelper';
import {threadContentsRoute, threadMessagesRoute} from '../../api-routes';
import {apiGet, apiPost} from '../../../../helpers/api';
import ThreadContent from '../../../../models/ThreadContent';

export const fetchThreadContents = getThunkActionCreator(
  fetchThreadContentsRoutine,
  async (threadId: number, page: number = 1) => {
    try {
      const { threadContents, meta } = await apiGet(
        threadContentsRoute(threadId),
        { page }
      );

      return {collection: plainToClass(ThreadContent, threadContents), meta};
    } catch (e) {
      AlertifyHelper.error('Unable to fetch thread contents');
      throw e;
    }
  }
);

export const postThreadContent = getThunkActionCreator(
  postThreadContentRoutine,
  async ({threadId, message}: {threadId: number, message: string}) => {
    try {
      // todo: append attachment ids
      const attachmentIds: number[] = [];
      const { threadContent } = await apiPost(threadMessagesRoute(threadId), {
        message,
        threadAttachments: attachmentIds
      });
      return plainToClass(ThreadContent, threadContent);
    } catch (e) {
      AlertifyHelper.error('Failed to send your message.');
      throw e;
    }
  }
);