import type { Observable } from '@apollo/client' import { ApolloLink } from '@apollo/client' import type { FetchResult, NextLink, Operation } from '@apollo/client/core' import type { GraphQLErrors, NetworkError } from '@apollo/client/errors' import type { ExecutionResult } from 'graphql' import pubsub from '../utils/pubsub' import { getGqlOperation } from '../utils' export interface ErrorResponse { graphQLErrors?: GraphQLErrors networkError?: NetworkError response?: ExecutionResult operation: Operation forward: NextLink } export type ErrorHandler = ( error: ErrorResponse, ) => Observable | null export function onTrack(): ApolloLink { return new ApolloLink((operation, forward) => { operation.setContext({ time: Date.now() }) return forward(operation).map(response => { // 接口调用跟踪,只针对正常调用的接口 try { !response.errors && pubsub.publish('ADD', getGqlOperation(operation)) } catch {} return response }) }) } /** * GraphQL接口调用追踪的自定义link */ export class CallLink extends ApolloLink { private link: ApolloLink public constructor() { super() this.link = onTrack() } public request( operation: Operation, forward: NextLink, ): Observable | null { return this.link.request(operation, forward) } }