RestfulSocket is a RESTful Socket that combines the native Fetch, Websocket and Promise API to create a restful response to a websocket event listener.
- Install RestfulSocket:
npm install --save restfulsocket
- Import RestfulSocket:
import RestfulSocket from 'restfulsocket'
- Use RestfulSocket:
// restSocket.socket => socket created from new WebSocket(...)
const onopen = () =>{
/* Function for socket on open */
restSocket.socket.send(...);
};
const onclose = () =>{ /* Function for socket on close */ };
const onerror = () =>{ /* Function for socket on error* /};
const restSocket = new RestfulSocket('ws://localhost/', onopen, onclose, onerror);
restSocket.findSocketMessage((socketMessageData) =>{
/* define a filter to find and return socket message from socketMessageData object */
});
restSocket.get('localhost/api/initialData', requestObjectOne)
.on('sampleMessage')
.then((data) => {
//DATA is an array of objects returned from fetch promises
})
.catch(console.log);
- Complex use case:
const restSocket = new RestfulSocket('ws://localhost/', onopen, onclose, onerror);
restSocket.findSocketMessage((socketMessageData) =>{
/* define a filter to find and return socket message from socketMessageData object */
});
restSocket.get('localhost/api/initialData', requestObjectOne)
.post('localhost/api/initialPost', requestObjectTwo)
.on('init')
.then((data) => {
//DATA is an array of objects returned from fetch promises
})
.catch(console.log);
restSocket.get('localhost/api/updateData', requestObjectThree)
.get('localhost/api/secondaryData', requestObjectFour)
.on('update')
.then((data) => {
//DATA is an array of objects returned from fetch promises
})
.catch(console.log);