UNPKG

integration-websocket-rest-api

Version:

A JavaScript library for easy integration of REST API and WebSocket communication with state management in JS applications.

58 lines (49 loc) 1.22 kB
// stateManagement.js const { createStore } = require("redux"); // Action types const WS_MESSAGE_RECEIVED = "WS_MESSAGE_RECEIVED"; const API_REQUEST_SUCCESS = "API_REQUEST_SUCCESS"; // Action creators const wsMessageReceived = (message) => ({ type: WS_MESSAGE_RECEIVED, payload: message, }); const apiRequestSuccess = (data) => ({ type: API_REQUEST_SUCCESS, payload: data, }); // Reducers const webSocketReducer = (state = { receivedMessages: [] }, action) => { switch (action.type) { case WS_MESSAGE_RECEIVED: return { ...state, receivedMessages: [...state.receivedMessages, action.payload], }; default: return state; } }; const apiReducer = (state = { responseData: null }, action) => { switch (action.type) { case API_REQUEST_SUCCESS: return { ...state, responseData: action.payload, }; default: return state; } }; // Combine reducers const rootReducer = (state = {}, action) => ({ webSocket: webSocketReducer(state.webSocket, action), api: apiReducer(state.api, action), }); // Create store const store = createStore(rootReducer); module.exports = { store, wsMessageReceived, apiRequestSuccess, };