UNPKG

8.44 kBMarkdownView Raw
1# graphql-request
2
3Minimal GraphQL client supporting Node and browsers for scripts or simple apps.
4
5![GitHub Action](https://github.com/jasonkuhrt/graphql-request/workflows/trunk/badge.svg) [![npm version](https://badge.fury.io/js/graphql-request.svg)](https://badge.fury.io/js/graphql-request)
6
7<!-- START doctoc generated TOC please keep comment here to allow auto update -->
8<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
9
10- [Highlights](#highlights)
11- [Install](#install)
12 - [TypeScript Setup](#typescript-setup)
13- [Quick Start](#quick-start)
14- [Examples](#examples)
15- [Node Version Support](#node-version-support)
16- [Reference](#reference)
17 - [Configuration](#configuration)
18 - [ErrorPolicy](#errorpolicy)
19 - [None (default)](#none-default)
20 - [Ignore](#ignore)
21 - [All](#all)
22 - [IgnoreOperationName](#ignoreoperationname)
23- [Knowledge Base](#knowledge-base)
24 - [Why was the file upload feature taken away? Will it return?](#why-was-the-file-upload-feature-taken-away-will-it-return)
25 - [Why do I have to install `graphql`?](#why-do-i-have-to-install-graphql)
26 - [Do I need to wrap my GraphQL documents inside the `gql` template exported by `graphql-request`?](#do-i-need-to-wrap-my-graphql-documents-inside-the-gql-template-exported-by-graphql-request)
27 - [What sets `graphql-request` apart from other clients like Apollo, Relay, etc.?](#what-sets-graphql-request-apart-from-other-clients-like-apollo-relay-etc)
28- [Project Stats](#project-stats)
29 - [Package Installs](#package-installs)
30 - [Repo Beats](#repo-beats)
31
32<!-- END doctoc generated TOC please keep comment here to allow auto update -->
33
34## Highlights
35
36- Most **simple & lightweight** GraphQL client
37- Promise-based API (works with `async` / `await`)
38- [Pure ESM package](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c)
39- First class TypeScript support
40 - Including `TypedDocumentNode`
41- Isomorphic (works in both Node and Browsers)
42
43## Install
44
45```sh
46npm add graphql-request graphql
47```
48
49#### TypeScript Setup
50
51This package uses [`package.exports`](https://www.typescriptlang.org/docs/handbook/modules/reference.html#packagejson-exports). Therefore if you are a TypeScript user you must:
52
531. have your `tsconfig.json` `moduleResolution` set to [`"bundler"`](https://www.typescriptlang.org/docs/handbook/modules/reference.html#bundler) or [`"node16"`/`"nodenext"`](https://www.typescriptlang.org/docs/handbook/modules/reference.html#node16-nodenext-1).
542. Have your `package.json` `type` set to `"module"`.
55
56## Quick Start
57
58Send a GraphQL document using a static request function:
59
60```js
61import { gql, request } from 'graphql-request'
62
63const document = gql`
64 {
65 company {
66 ceo
67 }
68 }
69`
70await request('https://api.spacex.land/graphql/', document)
71```
72
73The function can be passed a configuration object for more complex cases:
74
75```ts
76await request({
77 url,
78 document,
79 variables,
80 requestHeaders,
81})
82```
83
84A class is available for constructing your own instances:
85
86```js
87import { gql, GraphQLClient } from 'graphql-request'
88
89const document = gql`
90 {
91 company {
92 ceo
93 }
94 }
95`
96const endpoint = 'https://api.spacex.land/graphql/'
97const client = new GraphQLClient(endpoint)
98await client.request(document)
99```
100
101## Examples
102
103- Request:
104 - [Authentication via HTTP header](./examples/request-authentication-via-http-header.ts)
105 - [Method GET](./examples/request-method-get.ts)
106 - [Cancellation](./examples/request-cancellation.ts)
107 - [Headers Per Request (static)](./examples/request-headers-static-per-request.ts)
108 - [Headers Per Request (dynamic)](./examples/request-headers-dynamic-per-request.ts)
109 - [Handle Raw Response](./examples/request-handle-raw-response.ts)
110- GraphQL:
111 - [Document Variables](./examples/graphql-document-variables.ts)
112 - [Mutation](./examples/graphql-mutations.ts)
113 - [Batching Requests](./examples/graphql-batching-requests.ts)
114- Configuration:
115 - [Fetch: Passing Options](./examples/configuration-fetch-options.ts)
116 - [Custom JSON Serializer](./examples/configuration-request-json-serializer.ts)
117 - [Incremental: Set Endpoint](./examples/configuration-incremental-endpoint.ts)
118 - [Incremental: Set Request Headers](./examples/configuration-incremental-request-headers.ts)
119- TypeScript:
120 - [Use `TypedDocumentNode`](./examples/typescript-typed-document-node.ts)
121- Other:
122 - [Middleware](./examples/other-middleware.ts)
123 - [Error Handling](./examples/other-error-handling.ts)
124
125## Node Version Support
126
127We only (officially) support [versions of Nodejs](https://github.com/nodejs/Release#release-schedule) of the following status:
128
129- Current
130- LTS
131- Maintenance _and end of life not yet reached_
132
133So for example on Oct 24 2023 that would mean these versions: 18, 20, 21.
134
135Any issue that exists solely for an unsupported version of Nodejs will be rejected (not worked on).
136
137## Reference
138
139⚠️ This reference is incomplete. Check out the [examples](./examples/) for more reference material.
140
141### Configuration
142
143#### ErrorPolicy
144
145By default GraphQLClient will throw when an error is received. However, sometimes you still want to resolve the (partial) data you received.
146You can define `errorPolicy` in the `GraphQLClient` constructor.
147
148```ts
149const client = new GraphQLClient(endpoint, { errorPolicy: 'all' })
150```
151
152##### None (default)
153
154Allow no errors at all. If you receive a GraphQL error the client will throw.
155
156##### Ignore
157
158Ignore incoming errors and resolve like no errors occurred
159
160##### All
161
162Return both the errors and data, only works with `rawRequest`.
163
164### IgnoreOperationName
165
166OperationName has been introduced to address issues reported here [Support operation name](https://github.com/jasonkuhrt/graphql-request/issues/64),
167However, on certain occasions this information may not be needed in requests. In such cases, you might consider ignoring operationName to avoid the extraction steps currently performed by a parsing operation when the document is provided in string format.
168
169By default the GraphQLClient tries to extract the operationName from the document.
170You can define `excludeOperationName` in the constructor of GraphQLClient to avoid the extraction process if it is not needed. This can be useful if you don't use operationName and want to optimise queries by reducing the amount of computation as much as possible, especially if we are in a context where we are using documents in string format to reduce bundle size.
171
172```ts
173// example where the operation name is not ignored
174const client = new GraphQLClient(endpoint, {
175 method: 'POST',
176})
177// example in which the operation name is ignored
178const client = new GraphQLClient(endpoint, {
179 method: 'POST',
180 excludeOperationName: true,
181})
182```
183
184## Knowledge Base
185
186#### Why was the file upload feature taken away? Will it return?
187
188In [this issue](https://github.com/jasonkuhrt/graphql-request/issues/500) we decided to make this library more stable and maintainable. In principal the feature is still in scope of this library and will make a return when we find time to do the feature right.
189
190#### Why do I have to install `graphql`?
191
192`graphql-request` uses methods exposed by the `graphql` package to handle some internal logic. On top of that, for TypeScript users, some types are used from the `graphql` package to provide better typings.
193
194#### Do I need to wrap my GraphQL documents inside the `gql` template exported by `graphql-request`?
195
196No. It is there for convenience so that you can get the tooling support like automatic formatting and syntax highlighting. You can use `gql` from `graphql-tag` if you need it for some reason too.
197
198#### What sets `graphql-request` apart from other clients like Apollo, Relay, etc.?
199
200`graphql-request` is the most minimal and simplest to use GraphQL client. It's perfect for small scripts or simple apps.
201
202Compared to GraphQL clients like Apollo or Relay, `graphql-request` doesn't have a built-in cache and has no integrations for frontend frameworks. The goal is to keep the package and API as minimal as possible.
203
204## Project Stats
205
206### Package Installs
207
208<a href="https://npm-compare.com/graphql-request#timeRange=FIVE_YEARS" target="_blank">
209 <img src="https://npm-compare.com/img/npm-trend/FIVE_YEARS/graphql-request.png" width="100%" alt="NPM Usage Trend of graphql-request" />
210</a>
211
212### Repo Beats
213
214![Alt](https://repobeats.axiom.co/api/embed/aeb7beaee43b190e90868357c5a2898f517fb63e.svg "Repobeats analytics image")