Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import type { DocumentNode } from 'graphql';
import { parse } from 'graphql';
/**
* Extracts the operation name from a GraphQL query/mutation string
*/
export const extractOperationName = (query: string): string | null => {
try {
const parsedQuery: DocumentNode = parse(query);
const firstDefinition = parsedQuery.definitions[0];
if (
firstDefinition?.kind === 'OperationDefinition' &&
firstDefinition.selectionSet.selections.length > 0
) {
const firstSelection = firstDefinition.selectionSet.selections[0];
if (firstSelection.kind === 'Field') {
return firstSelection.name.value;
}
}
} catch (error) {
console.error('Error parsing GraphQL query:', error);
}
return null;
};
/**
* Get GraphQL query string from Request body
*/
export const getQueryFromRequest = async (
req: Request,
): Promise<string | null> => {
try {
// Using Next.js Request API
const body = await req.clone().json();
return body.query || null;
} catch (error) {
console.error('Error reading request body:', error);
return null;
}
};
/**
* Extracts the operation name from the GraphQL request
* First checks the body.operationName, if not present, parses the query.
*/
export const getOperationNameFromRequest = async (
req: Request,
): Promise<string | null> => {
try {
const body = await req.clone().json();
// if operationName is directly provided
if (body.operationName) {
return body.operationName;
}
// If not, parse it from the query string
if (body.query) {
return extractOperationName(body.query);
}
return null;
} catch (error) {
console.error('Error extracting operation name from request:', error);
return null;
}
};
/**
* Checks if a request is an introspection query
*/
export const isIntrospectionQuery = (operationName: string | null): boolean => {
return operationName === 'IntrospectionQuery';
};
|