Daydreams Logo
Extra reading

providers/api.ts

This file provides helper functions for interacting with external APIs within your agent's actions or services. The main exported function is fetchGraphQL, designed specifically to simplify making requests to GraphQL APIs.

How to Use

If you need to query a GraphQL endpoint from an action handler, you can import fetchGraphQL from @daydreamsai/core.

import { action, fetchGraphQL } from "@daydreamsai/core";
import type { AnyAgent, ActionCallContext } from "@daydreamsai/core";
 
const GRAPHQL_ENDPOINT = "https://api.example.com/graphql";
 
interface UserData {
  user: { id: string; name: string };
}
 
export const getUserAction = action({
  name: "getUserData",
  schema: z.object({ userId: z.string() }),
  async handler(args, ctx: ActionCallContext, agent: AnyAgent) {
    const query = `
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
        }
      }
    `;
    const variables = { id: args.userId };
 
    try {
      const result = await fetchGraphQL<UserData>(
        GRAPHQL_ENDPOINT,
        query,
        variables
      );
 
      if (result instanceof Error) {
        agent.logger.error("getUserAction", "GraphQL query failed", {
          error: result.message,
        });
        return { success: false, error: result.message };
      }
 
      agent.logger.info("getUserAction", "Got user data", {
        user: result.user,
      });
      return { success: true, userData: result.user };
    } catch (error) {
      agent.logger.error("getUserAction", "Fetch failed", { error });
      return { success: false, error: "Network error" };
    }
  },
});

Benefit

fetchGraphQL handles the boilerplate of setting up a GraphQL POST request (setting headers, stringifying the query and variables). It also provides basic error handling, returning an Error object if the GraphQL response indicates errors, which you can check for using instanceof Error. This makes interacting with GraphQL APIs from your actions cleaner and less error-prone than using fetch directly for this specific case.

Anticipated Questions

  • "Is there a helper for REST APIs?" While api.ts contains a fetchRest function, it doesn't seem to be exported directly via @daydreamsai/core. For general REST calls, you would typically use the http helper object (from http.ts) which provides automatic retries, or the standard fetch API.
  • "How does this differ from the http helper?" The http object provides general-purpose HTTP request helpers (GET, POST, JSON) with automatic retries. fetchGraphQL is specifically tailored for the GraphQL protocol, formatting the request body correctly and performing basic GraphQL-specific error checks on the response.

On this page