From 8f40d57a0fdc96b16574391726b0af84bc7992f8 Mon Sep 17 00:00:00 2001 From: Michael Zetterberg Date: Thu, 10 Oct 2024 17:50:16 +0200 Subject: [PATCH] feat: add improved logging for graphql requests --- lib/graphql/_request.ts | 61 +++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/lib/graphql/_request.ts b/lib/graphql/_request.ts index 8b9e94392..96246e453 100644 --- a/lib/graphql/_request.ts +++ b/lib/graphql/_request.ts @@ -53,13 +53,28 @@ export async function request( } } - const print = (await import("graphql/language/printer")).print - const nr = Math.random() - console.log(`START REQUEST ${nr}`) - console.time(`OUTGOING REQUEST ${nr}`) - console.log(`Sending reqeust to ${env.CMS_URL}`) - console.log(`Query:`, print(query as DocumentNode)) - console.log(`Variables:`, variables) + try { + // @ts-expect-error: query can be undefined (?) + const operationName = (query as DocumentNode).definitions.find( + (d) => d.kind === "OperationDefinition" && d.operation === "query" + // @ts-expect-error: name does not exist (?) + ).name.value + + console.log(`[gql] Sending graphql request to ${env.CMS_URL}`, { + operationName, + variables, + }) + } catch (e) { + console.error(`[gql] Unable to extract operation name from query`, { + query, + error: e, + }) + + console.log(`[gql] Sending graphql request to ${env.CMS_URL}`, { + operationName: "", + variables, + }) + } const response = await client.request({ document: query, @@ -70,8 +85,30 @@ export async function request( variables, }) - console.timeEnd(`OUTGOING REQUEST ${nr}`) - console.log({ response }) + try { + // @ts-expect-error: query can be undefined (?) + const operationName = (query as DocumentNode).definitions.find( + (d) => d.kind === "OperationDefinition" && d.operation === "query" + // @ts-expect-error: name does not exist (?) + ).name.value + + console.log(`[gql] Response for ${env.CMS_URL}`, { + response, + operationName, + variables, + }) + } catch (e) { + console.error(`[gql] Unable to extract operation name from query`, { + query, + error: e, + }) + + console.log(`[gql] Response for ${env.CMS_URL}`, { + response, + operationName: "", + variables, + }) + } return { data: response } } catch (error) { @@ -98,8 +135,10 @@ export async function request( } } - // console.error("Error in graphql request") - // console.error(error) + console.error( + `[gql] Error sending graphql request to ${env.CMS_URL}`, + error + ) throw new Error("Something went wrong") } }