chat-service.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { createContext } from 'react';
  2. import { ChatMessage } from '../interfaces/chat-message.model';
  3. import { getUnauthedData } from '../utils/apis';
  4. const ENDPOINT = `/api/chat`;
  5. const URL_CHAT_REGISTRATION = `/api/chat/register`;
  6. export interface UserRegistrationResponse {
  7. id: string;
  8. accessToken: string;
  9. displayName: string;
  10. displayColor: number;
  11. }
  12. export interface ChatStaticService {
  13. getChatHistory(accessToken: string): Promise<ChatMessage[]>;
  14. registerUser(username: string): Promise<UserRegistrationResponse>;
  15. }
  16. class ChatService {
  17. public static async getChatHistory(accessToken: string): Promise<ChatMessage[]> {
  18. try {
  19. const response = await getUnauthedData(`${ENDPOINT}?accessToken=${accessToken}`);
  20. return response;
  21. } catch (e) {
  22. return [];
  23. }
  24. }
  25. public static async registerUser(username: string): Promise<UserRegistrationResponse> {
  26. const options = {
  27. method: 'POST',
  28. headers: {
  29. 'Content-Type': 'application/json',
  30. },
  31. body: JSON.stringify({ displayName: username }),
  32. };
  33. const response = await getUnauthedData(URL_CHAT_REGISTRATION, options);
  34. return response;
  35. }
  36. }
  37. export const ChatServiceContext = createContext<ChatStaticService>(ChatService);