function eventSource(eventSource, events = []) {
const subs = emitter => {
eventSource.onmessage = (msg) => {
//return emitter(msg);
};
eventSource.onerror = () => {
return emitter(END)
};
console.log(events);
eventSource.addEventListener('disconnect', (event) => emitter({type: 'DISCONNECT', payload: JSON.parse(event.data)}), false);
events.map((eventType, index) => {
console.log(eventType);
return eventSource.addEventListener(eventType, (event) => emitter({type: eventType, payload: JSON.parse(event.data)}), false)
});
return () => {
return eventSource.close();
}
};
return eventChannel(subs);
}
function* itemsEventSource(formData){
let result;
try {
const params = new URLSearchParams();
params.append('clientId', formData.clientID);
params.append('access_token', formData.token);
result = new EventSource([SOCKET, 'notify'].join("/") + "?" + params.toString());
const channel = yield call(eventSource, result, [CONNECTED, DISCONNECTED, FETCH_SUCCESS, 'NOTIFY']);
while (true) {
const action = yield take(channel);
yield put(action);
}
} catch (error) {
yield put({type: CONNECT_FAILED, error: error.message});
}
return result;}
function* watchItemsEventSource() {
while (true) {
try {
const {payload} = yield take(CONNECT);
const [connect, cancel] = yield race(
[
call(itemsEventSource, payload),
take(CONNECT_FAILED)
]);
console.log(connect, cancel, payload);
} catch (error) {
yield put({type: ERROR, error: error.message});
}
}}
export function *moduleASaga(){
yield all({[ fork(watchItemsEventSource)]}) }