将GraphQL Header从请求传递到后续Axios请求

kiayqfof  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(130)

我有一个Angular应用程序,它使用Apollo Client从NestJS应用程序查询GraphQL Server。这个NestJS应用程序通过Axios向外部后端执行请求。
如何通过Axios将所有GraphQL请求中的客户端头集传递给后端请求?
Apollo客户端GraphQL请求> NestJS Apollo服务器GraphQL解析器> Axios HTTP请求。

// Configure the Apollo Client with custom Authorization header
function createApollo() {
  const { api } = AngularConfigService.getConfig();

  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        Authorization: `Bearer ${localStorage.getItem('jwt_token')}`,
      },
    };
  });

  return {
    link: authLink.concat(
      new HttpLink({ uri: `${api?.host}:${api?.port}/graphql` }),
    ),
    cache: new InMemoryCache({ addTypename: false }),
    defaultOptions: {
      // more content here ...
    } as DefaultOptions,
  };
}

@NgModule({
  imports: [],
  providers: [
    Apollo,
    { provide: APOLLO_OPTIONS, useFactory: createApollo, },
  ]
})

字符串
在Angular应用服务中,我向GraphQL服务器请求如下:

getUsers(args: GraphQL.QueryUsersArgs) {
   return this.graphQLDataService.query<GraphQL.UserDto[]>(usersQuery, args); // where usersQuery contains the GraphQL users query
}


我通过NestJS服务器中的以下服务方法将请求从GraphQL服务器连接到Axios:

getAllUsers(
  args: UsersArgsDto,
): Observable<DataResponse<UserDto[]>> {
  const queryParams = new URLSearchParams();

  this.getQueryFilterParams<UsersQueryFilterInput>(
    queryParams,
    args.queryFilters,
  );
  this.getPaginationParams(queryParams, args.pagination);
  this.getSortingParams(queryParams, args.sort);

  return this.httpService
    .get('/users', {
      ...this.globalConfig,
      params: queryParams,
    })
    .pipe(
      map((data) => data.data),
      validateObject(DataResponse<UsersDto[]>),
      catchError((err) => {
        throw err;
      }),
    );
}


我可以通过查询或突变中的上下文访问GraphQL请求头,但我无法访问链接到该请求的Axios HTTP请求。
是否可以传递到HTTP上下文?

epggiuax

epggiuax1#

最后,我使用了以下服务:

@Injectable({ scope: Scope.REQUEST })
export class GraphQLContextService {
  constructor(@Inject(CONTEXT) context: GraphQLCustomExecutionContext) {}

  getContextRequestHeaders() {
    return this.context.req.headers;
  }
}

字符串
然后我可以在所需的服务中使用:

constructor(private readonly gqlContextService: GraphQLContextService)

getAllUsers(
  args: UsersArgsDto,
): Observable<DataResponse<UserDto[]>> {
  const queryParams = new URLSearchParams();

  this.getQueryFilterParams<UsersQueryFilterInput>(
    queryParams,
    args.queryFilters,
  );
  this.getPaginationParams(queryParams, args.pagination);
  this.getSortingParams(queryParams, args.sort);

  return this.httpService
    .get('/users', {
      ...this.globalConfig,
      params: queryParams,
      // Here we can link the GraphQL Headers to the Axios request
      headers: this.gqlContextService.getContextRequestHeaders(); 
    })
    .pipe(
      map((data) => data.data),
      validateObject(DataResponse<UsersDto[]>),
      catchError((err) => {
        throw err;
      }),
    );
}

相关问题