我需要记录RTK-Query所做的所有API调用
我知道我们可以使用redux-logger记录所有的状态变化到控制台用于开发目的。但我需要记录所有的状态变化/API调用由RTK查询。
我看到RTK Query在底层使用fetch,所以不能有一个拦截器来做这项工作。我也不想用axios库代替fetch来引入拦截器。
另一个我不打算使用的选项是覆盖windows的console.log来执行到服务器端点的日志记录。
我看到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>;
我能想到的记录所有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)
);```
在RTK Query中,您不会像在axios中那样使用拦截器,但您会包装baseQuery
函数:
const originalBaseQuery = fetchBaseQuery({ /* your config */ })
const wrappedBaseQuery = (...args) => {
console.log ("making api call", ...args)
return originalBaseQuery (...args)
}
createApi({
baseQuery: wrappedBaseQuery ,
// ...
})