UNPKG

integration-websocket-rest-api

Version:

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

70 lines (60 loc) 1.58 kB
const { createStore } = require("redux"); // Action types const WS_MESSAGE_RECEIVED = "WS_MESSAGE_RECEIVED"; const API_REQUEST_SUCCESS = "API_REQUEST_SUCCESS"; const API_REQUEST_FAILURE = "API_REQUEST_FAILURE"; // Add new action type for API request failure // Action creators const wsMessageReceived = (message) => ({ type: WS_MESSAGE_RECEIVED, payload: message, }); const apiRequestSuccess = (data) => ({ type: API_REQUEST_SUCCESS, payload: data, }); const apiRequestFailure = (error) => ({ type: API_REQUEST_FAILURE, payload: error, }); // 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, error: null }, action) => { switch (action.type) { case API_REQUEST_SUCCESS: return { ...state, responseData: action.payload, error: null, // Clear error on successful request }; case API_REQUEST_FAILURE: return { ...state, error: 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, apiRequestFailure, };