logo

GraphQlAPI

The GraphQlAPI class extends the RestAPI class and manages the requests to a GraphQL API.

  • The base URL of the API is automatically concatenated to the path of the requests.
  • The config of the API is automatically merged with the config of the requests.
  • The status of the requests is automatically tracked and can be accessed through the status property.
  • The requests are sent with the Fetch class, so all features of the Fetch class are available.

Properties

  • baseURL (string): The base URL of the GraphQL API. This is the URL that will be prepended to all request paths.
  • config (T extends GraphQlApiConfig): The default configuration for the GraphQL API. This configuration will be merged with the configuration of individual requests.
  • status (Status): The status of the requests. This property tracks the status of each request (e.g., pending, success, error) and can be accessed to check the status of a request.

Send a query

The query method is used to send a query to the GraphQL API.

import { GraphQlAPI } from '@aracna/core';

const api = new GraphQlAPI('https://graphqlzero.almansi.me/api');

(async () => {
  let query, response;

  query =
    'query getUsers($limit: Int) { users(options: { paginate: { limit: $limit } }) { data { email id name username } } }';

  response = await api.query(query);
  if (response instanceof Error) return;

  // will log FetchResponse
  console.log(response.data);
})();

Send a mutation

The mutation method is used to send a mutation to the GraphQL API.

import { GraphQlAPI } from '@aracna/core';

const api = new GraphQlAPI('https://graphqlzero.almansi.me/api');

(async () => {
  let query, variables, response;

  query =
    'mutation createUser($email: String!, $name: String!, $username: String!) { createUser(input: { email: $email, name: $name, username: $username }) { email id name username } }';

  variables = {
    email: 'john.doe@email.com',
    name: 'John Doe',
    username: 'john.doe'
  };

  response = await api.mutation(query, variables);
  if (response instanceof Error) return;

  // will log FetchResponse
  console.log(response.data);
})();