2023-02-27 03:54:28 +03:00
|
|
|
import { createContext } from 'react';
|
2022-04-30 01:09:53 +03:00
|
|
|
import { ChatMessage } from '../interfaces/chat-message.model';
|
2022-05-03 03:45:22 +03:00
|
|
|
import { getUnauthedData } from '../utils/apis';
|
2022-07-21 06:42:23 +03:00
|
|
|
|
2022-05-09 09:28:54 +03:00
|
|
|
const ENDPOINT = `/api/chat`;
|
|
|
|
const URL_CHAT_REGISTRATION = `/api/chat/register`;
|
2022-04-27 00:04:35 +03:00
|
|
|
|
2023-02-27 03:54:28 +03:00
|
|
|
export interface UserRegistrationResponse {
|
2022-04-27 00:04:35 +03:00
|
|
|
id: string;
|
|
|
|
accessToken: string;
|
|
|
|
displayName: string;
|
2022-08-10 05:56:45 +03:00
|
|
|
displayColor: number;
|
2022-04-27 00:04:35 +03:00
|
|
|
}
|
|
|
|
|
2023-02-27 03:54:28 +03:00
|
|
|
export interface ChatStaticService {
|
|
|
|
getChatHistory(accessToken: string): Promise<ChatMessage[]>;
|
|
|
|
registerUser(username: string): Promise<UserRegistrationResponse>;
|
|
|
|
}
|
|
|
|
|
2022-04-30 01:09:53 +03:00
|
|
|
class ChatService {
|
|
|
|
public static async getChatHistory(accessToken: string): Promise<ChatMessage[]> {
|
2023-03-14 01:23:14 +03:00
|
|
|
try {
|
|
|
|
const response = await getUnauthedData(`${ENDPOINT}?accessToken=${accessToken}`);
|
|
|
|
return response;
|
|
|
|
} catch (e) {
|
|
|
|
return [];
|
|
|
|
}
|
2022-04-30 01:09:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
public static async registerUser(username: string): Promise<UserRegistrationResponse> {
|
2022-04-27 00:04:35 +03:00
|
|
|
const options = {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
body: JSON.stringify({ displayName: username }),
|
|
|
|
};
|
2022-04-28 09:19:20 +03:00
|
|
|
|
2022-05-03 08:13:36 +03:00
|
|
|
const response = await getUnauthedData(URL_CHAT_REGISTRATION, options);
|
|
|
|
return response;
|
2022-04-27 00:04:35 +03:00
|
|
|
}
|
2022-04-28 09:19:20 +03:00
|
|
|
}
|
2022-04-30 01:09:53 +03:00
|
|
|
|
2023-02-27 03:54:28 +03:00
|
|
|
export const ChatServiceContext = createContext<ChatStaticService>(ChatService);
|