1import type {
2 NamedTypeNode,
3 NameNode,
4 DirectiveNode,
5 SelectionNode,
6 SelectionSetNode,
7 FieldNode,
8 FragmentDefinitionNode,
9} from '@0no-co/graphql.web';
10
11import type { FormattedNode } from '@urql/core';
12
13export type SelectionSet = readonly FormattedNode<SelectionNode>[];
14
15const EMPTY_DIRECTIVES: Record<string, DirectiveNode | undefined> = {};
16
17/** Returns the directives dictionary of a given node */
18export const getDirectives = (node: {
19 _directives?: Record<string, DirectiveNode | undefined>;
20}) => node._directives || EMPTY_DIRECTIVES;
21
22/** Returns the name of a given node */
23export const getName = (node: { name: NameNode }): string => node.name.value;
24
25export const getFragmentTypeName = (node: FragmentDefinitionNode): string =>
26 node.typeCondition.name.value;
27
28/** Returns either the field's name or the field's alias */
29export const getFieldAlias = (node: FieldNode): string =>
30 node.alias ? node.alias.value : node.name.value;
31
32const emptySelectionSet: SelectionSet = [];
33
34/** Returns the SelectionSet for a given inline or defined fragment node */
35export const getSelectionSet = (node: {
36 selectionSet?: FormattedNode<SelectionSetNode>;
37}): FormattedNode<SelectionSet> =>
38 (node.selectionSet
39 ? node.selectionSet.selections
40 : emptySelectionSet) as FormattedNode<SelectionSet>;
41
42export const getTypeCondition = (node: {
43 typeCondition?: NamedTypeNode;
44}): string | null =>
45 node.typeCondition ? node.typeCondition.name.value : null;