Skip to content

Commit

Permalink
fix: adding nested input variables in graphql plugin
Browse files Browse the repository at this point in the history
GraphQL inputs are frequently nested like:
{
  "input": {
    "value1": 1,
    "value2": 2
  }
}

Currently this would result the following call:
span.setAttribute("input", Object({ value1: 1, value2: 2}))
But since SpanAttribute doesn't accept an Object type it silently fails
and doesn't add the attribute at all.

This commit goes depth-first into the nested structure and adds each
variable with the appropriate path.
  • Loading branch information
bodymindarts committed Nov 5, 2021
1 parent 62a04c7 commit 8290025
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
Maybe,
} from './types';
import {
addInputVariableAttributes,
addSpanSource,
endSpan,
getOperation,
Expand Down Expand Up @@ -419,9 +420,7 @@ export class GraphQLInstrumentation extends InstrumentationBase {
}

if (processedArgs.variableValues && config.allowValues) {
Object.entries(processedArgs.variableValues).forEach(([key, value]) => {
span.setAttribute(`${AttributeNames.VARIABLES}${String(key)}`, value);
});
addInputVariableAttributes(span, processedArgs.variableValues);
}

return span;
Expand Down
25 changes: 25 additions & 0 deletions plugins/node/opentelemetry-instrumentation-graphql/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,31 @@ import {

const OPERATION_VALUES = Object.values(AllowedOperationTypes);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function addInputVariableAttribute(span: api.Span, key: string, variable: any) {
if (Array.isArray(variable)) {
variable.forEach((value, idx) => {
addInputVariableAttribute(span, `${key}.${idx}`, value);
});
} else if (variable instanceof Object) {
Object.entries(variable).forEach(([nestedKey, value]) => {
addInputVariableAttribute(span, `${key}.${nestedKey}`, value);
});
} else {
span.setAttribute(`${AttributeNames.VARIABLES}${String(key)}`, variable);
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function addInputVariableAttributes(
span: api.Span,
variableValues: { [key: string]: any }
) {
Object.entries(variableValues).forEach(([key, value]) => {
addInputVariableAttribute(span, key, value);
});
}

export function addSpanSource(
span: api.Span,
loc?: graphqlTypes.Location,
Expand Down

0 comments on commit 8290025

Please sign in to comment.