2024-06-04 09:31:37 +01:00
|
|
|
import { createAction, createFeatureSelector, createReducer, createSelector, on, props } from "@ngrx/store";
|
2024-06-04 16:26:03 +01:00
|
|
|
import { TableRoom } from "./rooom-local-data-source.service";
|
|
|
|
|
import { RoomOutPutDTO } from "../../dto/room/roomOutputDTO";
|
2024-06-04 09:31:37 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
export interface ChatRoom {
|
2024-06-04 16:26:03 +01:00
|
|
|
[roomId: string]: TableRoom[];
|
2024-06-04 09:31:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface RoomRemoteDataSourceState {
|
|
|
|
|
chatRooms: ChatRoom;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const initialState: RoomRemoteDataSourceState = {
|
|
|
|
|
chatRooms: {
|
|
|
|
|
// add more rooms as needed
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const addMessage = createAction(
|
|
|
|
|
'[Chat] Add Message',
|
|
|
|
|
props<{ roomId: string; message: any }>()
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export const addRoom = createAction(
|
|
|
|
|
'[Chat] Add Room',
|
2024-06-04 16:26:03 +01:00
|
|
|
props<RoomOutPutDTO>()
|
2024-06-04 09:31:37 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const _chatReducer = createReducer(
|
|
|
|
|
initialState,
|
|
|
|
|
on(addMessage, (state, { roomId, message }) => ({
|
|
|
|
|
...state,
|
|
|
|
|
chatRooms: {
|
|
|
|
|
...state.chatRooms,
|
|
|
|
|
[roomId]: [...(state.chatRooms[roomId] || []), message]
|
|
|
|
|
}
|
|
|
|
|
})),
|
2024-06-04 16:26:03 +01:00
|
|
|
on(addRoom, (state, roomData: RoomOutPutDTO) => ({
|
2024-06-04 09:31:37 +01:00
|
|
|
...state,
|
|
|
|
|
chatRooms: {
|
|
|
|
|
...state.chatRooms,
|
2024-06-04 16:26:03 +01:00
|
|
|
[roomData.data.roomName]: roomData.data
|
2024-06-04 09:31:37 +01:00
|
|
|
}
|
|
|
|
|
}))
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export function chatReducer(state, action) {
|
|
|
|
|
return _chatReducer(state, action);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a feature selector
|
|
|
|
|
export const selectChatState = createFeatureSelector<RoomRemoteDataSourceState>('chat');
|
|
|
|
|
|
|
|
|
|
// Create a selector for a specific room's messages
|
|
|
|
|
export const selectMessagesByRoom = (roomId: string) => createSelector(
|
|
|
|
|
selectChatState,
|
|
|
|
|
(state: RoomRemoteDataSourceState) => state.chatRooms[roomId] || []
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Create a selector for the list of rooms
|
|
|
|
|
export const selectAllRooms = createSelector(
|
|
|
|
|
selectChatState,
|
|
|
|
|
(state: RoomRemoteDataSourceState) => Object.keys(state.chatRooms)
|
|
|
|
|
);
|