登录后反应 Admin Saga

React Admin Saga after login

React-admin I want add a background task. Every 30 seconds or so, I want to check my API if there any new orders. If managed to set this up trough sagas 合作。缺点是,我希望它只在登录后 运行,并且只针对特定的用户类型。我不知道如何访问 saga 中的任何授权,也无法在文档或在线中找到任何相关信息。在注销时我想取消间隔。

这是我到目前为止的故事:

import {call, put, takeEvery} from "redux-saga/effects";
import {eventChannel} from "redux-saga";
import {showNotification} from 'react-admin';

const countdown = () => {
    return eventChannel(emitter => {
            const iv = setInterval(() => {
                const req = new Request(`http://my.api.url/orders`, {
                    method: 'GET',
                    headers: new Headers(
                        {
                            'Accept': 'application/json',
                            'Authorization': `Bearer nice_token`,
                        }
                    ),
                });
                fetch(req)
                    .then((response) => {
                        if (response.status < 200 || response.status >= 300) {
                            throw new Error(response.statusText);
                        }
                        return response.json();
                    })
                    .then((response) => {
                        emitter(response)
                    })
                    .catch(error => {
                        console.log(error);
                        // emitter(END)
                    });
            }, 30000);
            // The subscriber must return an unsubscribe function
            return () => {
                clearInterval(iv)
            }
        }
    )
}

export default function* newOrders() {
    const channel = yield call(countdown);
    yield takeEvery(channel, function* (response) {
        if (response.data.length) {
            yield put(showNotification('New order received'))
        }
    });
}

在 react-admin 中声明的 Redux 操作:USER_LOGIN, USER_LOGIN_SUCCESS, USER_LOGOUT。 检查您是否拥有它们,如果没有,您可以使用它们代替:REGISTER_RESOURCE, UNREGISTER_RESOURCE:

import {
    USER_LOGIN,
    USER_LOGIN_SUCCESS,
    USER_LOGOUT,
    REGISTER_RESOURCE,
    UNREGISTER_RESOURCE,
} from 'ra-core' 

const startStopSaga = () => function* () {
  while (true) {
    yield take(USER_LOGIN_SUCCESS) // or REGISTER_RESOURCE    

    let current_user = localStorage.getItem('current_user') // Manual rights check    
    if (!current_user.rights) {
      continue    
    }

    yield race({
      task: call(newOrders),
      cancel: take(USER_LOGOUT), // or UNREGISTER_RESOURCE   
    })
  }
}