It is Websocket Store
# npm
npm install socket-store
# yarn
yarn add socket-store
First, create a message handler.
Define the topic, callback for the topic, and default status. This will be provided in the store.
- createMessageHandler(key, callback, state)
- key : it will be subject of message.
- callback: it will works like reducer. it must return state!
- state: it is defualt state.
const talkHandler = createMessageHandler<string[], string>(
"talk",
(state, data) => {
return [...state, data];
},
[]
);
Next, create a socket store. Store gets two parameters for web sockets and message handlers.
//handlers = you can uses like this.
const talkHandler = createMessageHandler('talk', (state, data)=>[...state, data], []);
const tradingHandler = createMessageHandler('trade', (state,data)=>data, null);
const socket = new WebSocket("ws://localhost:3030");
const store = new SocketStore(socket, [talkHandler, tradingHandler]);
// key is messagehandlers key, data: any type
store.send({key: 'talk', data: {user:'nerd', message:'hello'});
// give to key of messageHandler, then receive state about key.
store.getState('talk');
// return state of 'talk' topic
// ex) [{user:'nerd',message:'hi'}, {user:'chanii',message:'Can you help me? '}, {user: 'nerd', message:'kk'}]
MIT