|
| 1 | +import produce from 'immer'; |
| 2 | +import { InputMessageTypes } from 'messages'; |
| 3 | +import { RoomInfo, UserSession } from 'dals' |
| 4 | + |
| 5 | +let userCollectionSession: UserSession[] = []; |
| 6 | +let roomCollectionSession: RoomInfo[] = []; |
| 7 | + |
| 8 | +export const isRoomAvailable = async (room: string): Promise<boolean> => |
| 9 | + !userCollectionSession.find((session) => session.room === room); |
| 10 | + |
| 11 | +export const saveRoomInfo = async (newRoomInfo: RoomInfo, action: string): Promise<void> => { |
| 12 | + const roomIndex: number = await getRoomIndexByName(newRoomInfo); |
| 13 | + const content: string = newRoomInfo.content; |
| 14 | + roomCollectionSession = |
| 15 | + roomIndex === -1 |
| 16 | + ? await insertRoom(newRoomInfo) |
| 17 | + : await updateRoomContent(roomIndex, content, action); |
| 18 | +}; |
| 19 | + |
| 20 | +export const getRoomContent = async (room: string): Promise<string> => { |
| 21 | + const roomInfo = roomCollectionSession.find( |
| 22 | + (roomInfo: RoomInfo) => roomInfo.room === room |
| 23 | + ); |
| 24 | + |
| 25 | + return roomInfo ? roomInfo.content : ''; |
| 26 | +}; |
| 27 | + |
| 28 | +const getRoomIndexByName = async (newRoomInfo: RoomInfo): Promise<number> => { |
| 29 | + return roomCollectionSession.findIndex( |
| 30 | + (roomInfo: RoomInfo) => roomInfo.room === newRoomInfo.room |
| 31 | + ); |
| 32 | +}; |
| 33 | + |
| 34 | +const updateRoomContent = async (index: number, content: string, action:string): Promise<RoomInfo[]> => { |
| 35 | + return produce(roomCollectionSession, (draftState: RoomInfo[]) => { |
| 36 | + switch (action) { |
| 37 | + case InputMessageTypes.TRAINER_APPEND_TEXT: |
| 38 | + draftState[index].content += '\n' + content; |
| 39 | + break; |
| 40 | + case InputMessageTypes.TRAINER_SET_FULL_TEXT: |
| 41 | + draftState[index].content = content; |
| 42 | + break; |
| 43 | + }; |
| 44 | + }); |
| 45 | +}; |
| 46 | + |
| 47 | +const insertRoom = async (newRoomInfo: RoomInfo): Promise<RoomInfo[]> => { |
| 48 | + return produce(roomCollectionSession, (draftState: RoomInfo[]) => { |
| 49 | + draftState.push(newRoomInfo); |
| 50 | + }); |
| 51 | +}; |
0 commit comments