Skip to content

GraphQL services and definitions

This guide describes how frontend code in app/frontend/src/ defines GraphQL operations and calls them through API services. Generation commands and generated-file rules are in Generating types. The examples use a made-up bookmarks module: they show the pattern, not existing code.

GraphQL API services

Keep transport in an API service under the module's api/ folder. A service owns the Apollo client call, variables, request context such as UTM URIs, and mapping the payload to what callers need. Components, composables, and stores call the service; they do not call apolloClient directly.

  • Export a class that receives ApolloClient<object> in its constructor, plus a singleton created with the shared client from @/src/shared/plugins/apolloClient. Export the singleton by name in a new module (export const bookmarkApi = ...); in an existing module follow its services, most of which still use a default export.
  • Type each method's parameters and return value; callers should not depend on the raw Apollo result.
  • Expose subscriptions as service methods that wrap useSubscription from @vue/apollo-composable. The owner of the subscription stops the previous one before starting another.

A typed mutation service:

import type { ApolloClient } from "@apollo/client/core";
import { BOOKMARK_CREATE_UTM } from "@/src/bookmarks/constants/utm";
import { createBookmarkMutation } from "@/src/bookmarks/graphql/mutations/createBookmark";
import type {
  CreateBookmarkMutation,
  CreateBookmarkMutationVariables,
} from "@/src/bookmarks/graphql/mutations/createBookmark.generated";
import type { Bookmark, BookmarkAttributes } from "@/src/bookmarks/types";
import apolloClient from "@/src/shared/plugins/apolloClient";
import { getGraphqlUriWithUtmParams } from "@/src/shared/utils/utm";

export class BookmarkApi {
  constructor(private readonly apolloClient: ApolloClient<object>) {}

  public async create(attributes: BookmarkAttributes): Promise<Bookmark> {
    const fallback = window.EasyLocale.getLocale("error_something_went_wrong");

    const { data } = await this.apolloClient.mutate<CreateBookmarkMutation, CreateBookmarkMutationVariables>({
      mutation: createBookmarkMutation,
      variables: { attributes },
      context: {
        uri: getGraphqlUriWithUtmParams(BOOKMARK_CREATE_UTM),
      },
    });

    const payload = data?.createBookmark;
    if (!payload) throw new Error(fallback);

    if (payload.errors?.length) {
      const validationMessage = payload.errors.flatMap(error => error.messages ?? []).join(" ");
      throw new Error(validationMessage || fallback);
    }
    if (!payload.bookmark) throw new Error(fallback);

    return payload.bookmark;
  }
}

export const bookmarkApi = new BookmarkApi(apolloClient);

Use generated variables and results

Type variables and results with the *.generated.ts types generated next to each definition, imported type-only, as described in Use generated GraphQL types. After changing a definition, regenerate the types (Generating types); never edit generated files by hand.

Separate transport failures from validation errors

A GraphQL request can fail in two different ways, and callers must handle both:

  • Transport and GraphQL errors. The shared client sets no errorPolicy for mutations, so mutate rejects with an ApolloError on a network failure or a top-level GraphQL error. Queries use errorPolicy: "all" (shared/constants/apolloClient.ts): network failures still reject, while GraphQL errors arrive in the result's errors next to partial data. The client's error link (shared/plugins/apolloClient.ts) logs both kinds but shows a notification only for a network failure, so a caller that catches the rejection resets its own state, notifies a top-level GraphQL error itself and does not notify a network failure a second time.
  • Validation errors. A rejected change resolves normally and returns its messages in the mutation payload's errors field. Check that field before treating the result as success.

A service either converts validation errors into a thrown error, as BookmarkApi.create does above, or returns the payload so the caller can branch on it. The code that starts the request owns the resulting loading and error state (Own loading and errors).

notifyOnGraphqlValidationErrors from shared/api/utils.ts only shows a notification per error and returns nothing. A notification alone does not establish success: decide success from the payload, not from the absence of a notification.

A caller of a service that returns the payload treats a missing payload as a failure, checks the payload errors, and only then treats the result as success. It notifies a rejected request unless the error link already did, and clears its loading state on every outcome:

import { ApolloError } from "@apollo/client/core";
import { notifyAPIError, notifyOnGraphqlValidationErrors } from "@/src/shared/api/utils";

const archiving = ref(false);

const archiveBookmark = async (id: string) => {
  archiving.value = true;

  try {
    const payload = await bookmarkApi.archive(id);
    if (!payload) throw new Error(window.EasyLocale.getLocale("error_something_went_wrong"));

    if (payload.errors?.length) {
      notifyOnGraphqlValidationErrors(payload);
      return;
    }

    bookmarks.value = bookmarks.value.filter(bookmark => bookmark.id !== id);
  } catch (error) {
    // The Apollo error link has already notified a network failure; it only logs GraphQL errors.
    if (!(error instanceof ApolloError && error.networkError)) notifyAPIError(error);
  } finally {
    archiving.value = false;
  }
};

GraphQL definitions

Keep definitions separate from services, in the module's graphql/ folder (see Module structure), with one definition per file.

Naming conventions (required)

For every definition under app/frontend/src/**/graphql/**, keep these names aligned:

Part Fragment Query Mutation Subscription
File fooBar.ts fooBar.ts fooBar.ts fooBar.ts
Exported const fooBarFragment fooBarQuery fooBarMutation fooBarSubscription
GraphQL name fragment FooBar on ... query fooBar(...) mutation fooBar(...) subscription fooBar(...)
Generated file fooBar.generated.ts fooBar.generated.ts fooBar.generated.ts fooBar.generated.ts
  • Fragment names are PascalCase. Operation names follow the casing already used in the target folder.
  • Keep naming consistent with neighboring files. Do not rename prefixes such as base*, available*, or full* unless a clear local pattern justifies it.
  • When renaming a definition file, update imports of both the source and the generated file.

Examples: fullBookmark.ts exports fullBookmarkFragment with fragment FullBookmark; createBookmark.ts exports createBookmarkMutation with mutation createBookmark.

Compose with fragments

Define a fragment for a field set used by more than one operation, and nest fragments where it helps. Interpolate every fragment a document spreads after its body:

import { gql } from "@apollo/client";
import { fullBookmarkFragment } from "@/src/bookmarks/graphql/fragments/fullBookmark";

export const bookmarksQuery = gql`
  query bookmarks($projectId: ID!) {
    bookmarks(projectId: $projectId) {
      ...FullBookmark
    }
  }

  ${fullBookmarkFragment}
`;

Return errors from mutations

Every mutation selects an errors field with the shared EasyError fragment, so services can detect validation errors:

import { gql } from "@apollo/client";
import { fullBookmarkFragment } from "@/src/bookmarks/graphql/fragments/fullBookmark";
import { easyErrorFragment } from "@/src/shared/graphql/fragments/error";

export const createBookmarkMutation = gql`
  mutation createBookmark($attributes: BookmarkAttributes!) {
    createBookmark(attributes: $attributes) {
      bookmark {
        ...FullBookmark
      }
      errors {
        ...EasyError
      }
    }
  }

  ${fullBookmarkFragment}
  ${easyErrorFragment}
`;

Use gql as a tagged template

Write definitions as gql`...`, never as gql(...). This is the project's enforced convention: the easy-rules/no-gql-function-call lint rule reports any function call of gql imported from @apollo/client.

Conditional fields: directives vs. optional plugin fields

Plugin-dependent data may be absent, so guard both the definition and the UI that renders it with an availability check and an appropriate empty or disabled state.

Use runtime directives when the field exists in the schema but is needed only sometimes. Declare a boolean variable, guard the field with @include, and let the caller pass the flag in variables:

export const bookmarksQuery = gql`
  query bookmarks($projectId: ID!, $withAuthor: Boolean!) {
    bookmarks(projectId: $projectId) {
      ...FullBookmark
      author @include(if: $withAuthor) {
        ...BaseUser
      }
    }
  }

  ${fullBookmarkFragment}
  ${baseUserFragment}
`;

Build the document dynamically only for fields of a plugin that may not be installed. Such fields are missing from the schema, so a directive cannot help: the server rejects a document that names an unknown field even when it would be skipped. This is the only accepted reason to call gql as a function. Insert the plugin fields only when the availability flag is on, and disable the rule on that single line. The caller passes the flag from the list of installed plugins:

import { gql } from "@apollo/client";

export const getBookmarksQuery = (checklistOn: boolean) => {
  const checklistFields = `
    easyChecklists {
      id
      name
    }`;

  const bookmarksQuery = `
    query bookmarks($projectId: ID!) {
      bookmarks(projectId: $projectId) {
        id
        ${checklistOn ? checklistFields : ""}
      }
    }`;

  // eslint-disable-next-line easy-rules/no-gql-function-call
  return gql(bookmarksQuery);
};

Generating types

TypeScript types are generated from the GraphQL schema and from your definitions, so every definition file gets typed results and variables.

bundle exec rake easyproject:graphql_generate

The task dumps the schema to app/frontend/src/shared/graphql_schema/schema.generated.graphql and then runs yarn codegen:graphql (configuration in codegen.ts). It writes:

  • app/frontend/src/shared/types/schemaTypes.generated.ts: all schema types.
  • A <name>.generated.ts file next to every definition under graphql/ folders, for example bookmarks.generated.ts with BookmarksQuery.

Run it after every change of the backend schema. When only frontend definitions changed and the dumped schema is present, yarn codegen:graphql regenerates the types without Rails. The generated files are git-ignored, so do not commit them, and never edit a *.generated.* file by hand.

Import generated types type-only, as described in Use generated GraphQL types.

Runtime schema enums

A runtime import of an enum from schemaTypes.generated.ts makes the build depend on that file, and the build fails when it has not been generated. Use the type-only import from the generated file and take runtime enum values from app/frontend/src/shared/types/schemaEnums.ts:

import { PROMPT_TEMPLATE_USED_FOR } from "@/src/shared/types/schemaEnums";
import type { PromptTemplateUsedFor } from "@/src/shared/types/schemaEnums";

if (usedFor === PROMPT_TEMPLATE_USED_FOR.WriteAssistant) {
  // runtime-safe enum comparison
}

Do not write import { PromptTemplateUsedFor } from "@/src/shared/types/schemaTypes.generated" for runtime comparisons.

To add an enum, export an uppercase constant and a PascalCase type in schemaEnums.ts, following the existing entries:

const PROMPT_TEMPLATE_USED_FOR_VALUES = {
  Ask: "ask",
  HelpdeskAssistant: "helpdesk_assistant",
  ReadAssistant: "read_assistant",
  WriteAssistant: "write_assistant",
} as const satisfies GraphqlEnumShape<SchemaEnumObject<"PromptTemplateUsedFor">>;

export const PROMPT_TEMPLATE_USED_FOR = PROMPT_TEMPLATE_USED_FOR_VALUES as GraphqlEnumObject<
  typeof PROMPT_TEMPLATE_USED_FOR_VALUES,
  SchemaEnum<"PromptTemplateUsedFor">
>;
export type PromptTemplateUsedFor = ObjectValues<typeof PROMPT_TEMPLATE_USED_FOR>;

With generated files present, yarn tsc checks the values against the schema and reports missing keys, extra keys and mismatched strings.