redux 如何记录RTK Query发出的所有API请求?

dkqlctbz  于 2023-04-12  发布在  其他
关注(0)|答案(3)|浏览(143)

我需要记录RTK-Query发出的所有API调用
我知道我们可以使用redux-logger来记录所有状态更改到控制台用于开发目的。但我需要记录RTK查询所做的所有状态更改/ API调用。
我看到RTK Query在引擎盖下使用了fetch,所以不能使用拦截器来完成这项工作。我也不想用axios库来取代fetch来引入拦截器。
另一个我不打算使用的选项是覆盖windows的console.log来记录服务器端点。
我看到有类似的东西提供的日志火箭,但我不想船上的太...
我有什么选择?

import logger from 'redux-logger'

import { rootReducer } from 'src/reducers/rootReducer';

const otherMiddlewares: any[] = [];

if (process.env.NODE_ENV === `development`) {
    otherMiddlewares.push(logger);
}

export const store = configureStore({
    reducer: rootReducer,
    devTools: process.env.NODE_ENV !== 'production',
    // The API slice generates a custom middleware which manages cache lifetimes and expiration
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(otherMiddlewares)
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
omvjsjqw

omvjsjqw1#

我能想到的一种记录所有Redux更改的方法是编写一个用于自定义日志记录的中间件

// Log the current state and action being dispatched
  logger.info("Current State:", store.getState());
  logger.info("Action:", action);

  // Call the next middleware in the chain
  const result = next(action);

  // Log the new state after the action has been processed
  logger.info("New State:", store.getState());

  // Return the result of the next middleware in the chain
  return result;
};

import { createStore, applyMiddleware } from "redux";
import loggerMiddleware from "./middleware/logger";
import rootReducer from "./reducers";

const store = createStore(
  rootReducer,
  applyMiddleware(loggerMiddleware)
);```
2lpgd968

2lpgd9682#

为了在不替换fetch或使用LogRocket等外部库的情况下记录RTK Query进行的所有API调用,您可以创建一个侦听RTK Query操作的自定义中间件。
以下是如何创建用于记录RTK查询API调用的自定义中间件:
创建自定义中间件函数:

const apiCallLoggerMiddleware = (storeAPI) => (next) => (action) => {
  if (action.type.startsWith('api/') && (action.type.endsWith('/pending') || action.type.endsWith('/fulfilled') || action.type.endsWith('/rejected'))) {
    console.log('API call:', action.type, action);
  }
  return next(action);
};

此中间件检查操作类型是否以'API/'开头(假设您的apiSlice命名为'api')并以'/pending'、'/fulfilled'或'/rejected'结尾,表明它是RTK Query API调用。如果是,则记录操作类型和操作对象。
将中间件添加到您的商店配置:

const otherMiddlewares: any[] = [apiCallLoggerMiddleware];

if (process.env.NODE_ENV === `development`) {
  otherMiddlewares.push(logger);
}

export const store = configureStore({
  reducer: rootReducer,
  devTools: process.env.NODE_ENV !== 'production',
  // The API slice generates a custom middleware which manages cache lifetimes and expiration
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(otherMiddlewares),
});

现在,每当使用RTK查询进行API调用时,自定义中间件都会将API调用操作记录到控制台。如果需要,您可以进一步自定义日志记录。

gywdnpxw

gywdnpxw3#

在RTK Query中,你不会像axios那样使用拦截器,但你会 Package baseQuery函数:

const originalBaseQuery = fetchBaseQuery({ /* your config */ })
const wrappedBaseQuery = (...args) => {
  console.log ("making api call", ...args)
  return originalBaseQuery (...args)
}

createApi({
  baseQuery: wrappedBaseQuery ,
  // ...
})

相关问题