11import { DocumentTypeDecoration } from "@graphql-typed-document-node/core" ;
22import type { GqlResponse , NextFetchRequestConfig } from "./helpers" ;
3+ import { trace } from "@opentelemetry/api" ;
34import {
45 createSha256 ,
56 defaultHeaders ,
@@ -12,6 +13,9 @@ type Options = {
1213 disableCache ?: boolean ;
1314} ;
1415
16+ // TODO: make version dynamic, or part of the release process
17+ const tracer = trace . getTracer ( "@labdigital/graphql-fetcher" , "0.3.0" ) ;
18+
1519export const initServerFetcher =
1620 ( url : string , options ?: Options ) =>
1721 /**
@@ -25,14 +29,18 @@ export const initServerFetcher =
2529 next : NextFetchRequestConfig = { }
2630 ) : Promise < GqlResponse < TResponse > > => {
2731 const query = astNode . toString ( ) ;
28- const operationName = extractOperationName ( query ) ;
32+ const operationName = extractOperationName ( query ) || "(GraphQL)" ;
2933
3034 if ( options ?. disableCache ) {
31- return gqlPost < TResponse > (
32- url ,
33- JSON . stringify ( { operationName, query, variables } ) ,
34- "no-store" ,
35- { ...next , revalidate : 0 }
35+ return tracer . startActiveSpan ( operationName , async ( span ) =>
36+ gqlPost < TResponse > (
37+ url ,
38+ JSON . stringify ( { operationName, query, variables } ) ,
39+ "no-store" ,
40+ { ...next , revalidate : 0 }
41+ ) . finally ( ( ) => {
42+ span . end ( ) ;
43+ } )
3644 ) ;
3745 }
3846
@@ -44,24 +52,29 @@ export const initServerFetcher =
4452 } ;
4553
4654 // Otherwise, try to get the cached query
47- const response = await gqlPersistedQuery < TResponse > (
48- url ,
49- getQueryString ( operationName , variables , extensions ) ,
50- cache ,
51- next
55+ return tracer . startActiveSpan ( operationName , async ( span ) =>
56+ gqlPersistedQuery < TResponse > (
57+ url ,
58+ getQueryString ( operationName , variables , extensions ) ,
59+ cache ,
60+ next
61+ )
62+ . then ( ( response ) => {
63+ // If it doesn't exist, do a POST request anyway and cache it.
64+ if ( response . errors ?. [ 0 ] ?. message === "PersistedQueryNotFound" ) {
65+ return gqlPost < TResponse > (
66+ url ,
67+ JSON . stringify ( { operationName, query, variables, extensions } ) ,
68+ cache ,
69+ next
70+ ) ;
71+ }
72+ return response ;
73+ } )
74+ . finally ( ( ) => {
75+ span . end ( ) ;
76+ } )
5277 ) ;
53-
54- // If it doesn't exist, do a POST request anyway and cache it.
55- if ( response . errors ?. [ 0 ] ?. message === "PersistedQueryNotFound" ) {
56- return gqlPost < TResponse > (
57- url ,
58- JSON . stringify ( { operationName, query, variables, extensions } ) ,
59- cache ,
60- next
61- ) ;
62- }
63-
64- return response ;
6578 } ;
6679
6780const gqlPost = < T > (
0 commit comments