aboutsummaryrefslogtreecommitdiff
path: root/source/library/graphql/operations.ts
blob: b34aeeee16fa7f4ce5ae060062bd2d82a780a4b7 (plain) (blame)
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
/*** IMPORT ------------------------------------------- ***/

import { parse } from "graphql";

/*** EXPORT ------------------------------------------- ***/

export type OperationInfo = {
  name: string | null;
  type: "mutation" | "query" | "subscription";
};

export function deriveTitle(query: string, ops: OperationInfo[]): string {
  const first = ops[0];

  if (first && first.name)
    return first.name;

  if (first)
    return first.type;

  const trimmed = query.trim();

  if (!trimmed)
    return "untitled";

  return trimmed.slice(0, 20);
}

export function parseOperations(query: string): OperationInfo[] {
  const trimmed = query.trim();

  if (!trimmed)
    return [];

  try {
    const doc = parse(trimmed);
    const ops: OperationInfo[] = [];

    for (const def of doc.definitions) {
      if (def.kind !== "OperationDefinition")
        continue;

      ops.push({
        name: def.name?.value ?? null,
        type: def.operation
      });
    }

    return ops;
  } catch {
    return [];
  }
}