【问题标题】:How to wrap graphqlRequestBaseQuery to handle an expiring access token in Redux-toolkit rtk-query graphql application?如何包装 graphqlRequestBaseQuery 以处理 Redux-toolkit rtk-query graphql 应用程序中过期的访问令牌?
【发布时间】:2022-11-19 10:48:55
【问题描述】:

有没有人有一个很好的例子来包装 graphql 请求基础查询,以便在访问令牌过期时刷新访问和刷新令牌?这是我到目前为止的代码。

我尝试包装 graphqlRequestBaseQuery 但我不确定参数应该使用打字稿。

import { createApi } from "@reduxjs/toolkit/query/react";
import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query";
import { ClientError } from "graphql-request";

import { RootState } from "../store";

const baseUrl = process.env.REACT_APP_TECHNOTES_API_HTTP_GRAPHQL;
const techNotesHttpAPI = baseUrl ? baseUrl : "http://localhost:4001/graphql";

const baseQuery = graphqlRequestBaseQuery<
  Partial<ClientError> & { statusCode: number; error: string }
>({
  url: techNotesHttpAPI,
  prepareHeaders: (headers, { getState }) => {
    const state = getState() as RootState;
    const token = state.auth.token;

    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }

    return headers;
  },
  customErrors: ({ name, stack, response }) => {
    const {
      message = "",
      statusCode = 500,
      error = "",
    } = response?.errors?.length
      ? response?.errors[0]?.extensions.response
      : {};

    return {
      name,
      message,
      statusCode,
      error,
      stack,
    };
  },
});

export const apiSlice = createApi({
  reducerPath: "api",
  baseQuery,
  tagTypes: ["User", "Note"],
  endpoints: () => ({}),
});

【问题讨论】:

    标签: graphql access-token rtk-query


    【解决方案1】:

    好的,让它工作但不得不恢复使用 GraphQLClient(graphql-request 版本 4.3.0),因为没有它我找不到设置 {credentials: "include"} 的方法。

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 2023-01-15
      • 2012-05-28
      • 2021-09-10
      • 2022-11-24
      • 2022-08-18
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多