在服务器端的 redux-saga 中将用户请求包装在自定义 API 中

Wrap user req in a custom API in redux-saga for server side

在处理身份验证的通用应用程序中,我们必须考虑每个用户都有自己的 cookie。 所以我们需要存储他的初始请求对象,以便能够用他的 cookie 装饰他未来的 API 调用。 我不知道如何用 redux-saga 处理它,我想这项工作应该在自定义中间件中完成,以注入一个将用户请求对象包装到每个 saga 中的对象,至少我认为它可以完成这项工作,但是我不知道如何完全实现它。

我在想类似的事情:

export function* loadUser(action, api) { // Inject the object that wrap the initial user request object here
  try {
    const user = yield call(api.loadUser, action.payload); // So the request would be decorated behind this call
    yield put(actions.loadUserSuccess(user));
  } catch(e) {
    yield put(actions.loadUserFail(e));
  }
}

export default function* rootUserSagas() {
  yield* takeLatest(LOAD_USER_REQUEST, loadUser);
}

我想创建商店的时候有事情要做

export function configureStore(initialState = {}, req) {
  const api = new Api(req);

  // Then what to do with the api object to get it back into sagas?

  const sagaMiddleware = createSagaMiddleware();

  const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware(sagaMiddleware)
  );

  sagaMiddleware.run(rootSaga);

  return store;
};

您可以将 api 对象传递给 运行 函数

  sagaMiddleware.run(rootSaga, api)

然后将对象传递给子 sagas

export default function* rootUserSagas(api) {
    yield* takeLatest(LOAD_USER_REQUEST, loadUser, api);
}

// loadUser will receive the action in the last position
function* loadUser(api, action) { ... }