aboutsummaryrefslogtreecommitdiff
path: root/source/library/state/schema.svelte.ts
blob: c5f148f62b4d585ac72b88071d960175917a68d0 (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
/*** IMPORT ------------------------------------------- ***/

import {
  buildClientSchema,
  getIntrospectionQuery,
  printSchema,
  type GraphQLSchema,
  type IntrospectionQuery
} from "graphql";

/*** UTILITY ------------------------------------------ ***/

import type { Fetcher } from "../fetcher/types.ts";

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

export class SchemaStore {
  error = $state<string | null>(null);
  loading = $state(false);
  schema = $state<GraphQLSchema | null>(null);
  sdl = $state<string>("");

  async introspect(fetcher: Fetcher) {
    this.loading = true;
    this.error = null;

    try {
      const result = await fetcher({ query: getIntrospectionQuery() });
      const data = (result as { data: IntrospectionQuery }).data;
      this.schema = buildClientSchema(data);
      this.sdl = printSchema(this.schema);
    } catch(err) {
      this.error = String(err);
    } finally {
      this.loading = false;
    }
  }
}