Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@ts-gql/fetch

Package Overview
Dependencies
Maintainers
2
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ts-gql/fetch

> A small wrapper over `fetch` to call GraphQL APIs with ts-gql's type-safety.

  • 0.1.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
2
Weekly downloads
 
Created
Source

@ts-gql/fetch

A small wrapper over fetch to call GraphQL APIs with ts-gql's type-safety.

import { createFetcher, GraphQLErrorResult, Fetcher } from "@ts-gql/fetch";
import { gql } from "@ts-gql/tag"
// or
import { gql } from "@ts-gql/tag/no-transform"

const fetchGraphQL = createFetcher("https://some-graphql-api");

const someQueryOrMutation = gql`...` as import(...).type;

const result = await fetchGraphQL({ operation: someQueryOrMutation });

If any GraphQL errors are returned, an instance of GraphQLErrorResult is thrown which has the data and errors on it.

If you want to change how the fetching occurs but keep the types, you can re-use the Fetcher type and write your own implementation like this:

import { GraphQLErrorResult, Fetcher } from "@ts-gql/fetch";
import { DocumentNode, print } from "graphql";

const fetchGraphQL: Fetcher = ((
  operation: DocumentNode,
  variables?: Record<string, unknown>
) => {
  return fetch("https://some-graphql-api", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      query: print(operation),
      variables,
    }),
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.errors?.length) {
        throw new GraphQLErrorResult(data.data, data.errors);
      }
      return data.data;
    });
}) as any;

When using @ts-gql/fetch, make sure to set "addTypename": false to your ts-gql config so that the generated types only include __typename in the returned fields if explicitly requested since @ts-gql/fetch won't implicitly add __typename like some other GraphQL clients.

FAQs

Package last updated on 15 Jan 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc