Skip to content

Commit

Permalink
chore: normalize docs (dedupe) (#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonkuhrt authored Apr 15, 2023
1 parent 3a38f48 commit 6b3396b
Show file tree
Hide file tree
Showing 23 changed files with 429 additions and 668 deletions.
722 changes: 70 additions & 652 deletions README.md

Large diffs are not rendered by default.

38 changes: 38 additions & 0 deletions examples/community-graphql-code-generator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* `graphql-request@^5` supports `TypedDocumentNode`, the typed counterpart of `graphql`'s `DocumentNode`.
*
* Installing and configuring GraphQL Code Generator requires a few steps in order to get end-to-end typed GraphQL operations using the provided `graphql()`.
*
* The complete example is available in the GraphQL Code Generator repository:
*
* @see https://github.com/dotansimha/graphql-code-generator/tree/master/examples/front-end/react/graphql-request
*
* Visit GraphQL Code Generator's dedicated guide to get started:
*
* @see https://www.the-guild.dev/graphql/codegen/docs/guides/react-vue.
*/

import request, { gql } from '../src/index.js'
// @ts-expect-error todo make this actually work
import { graphql } from './gql/gql'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

// todo fixme
// eslint-disable-next-line
const document = graphql(gql`
query getMovie($title: String!) {
Movie(title: $title) {
releaseDate
actors {
name
}
}
}
`)

// Variables are typed!
const data = await request(endpoint, document, { title: `Inception` })

// @ts-expect-error todo make this actually work
console.log(data.Movie) // typed!
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { gql, GraphQLClient } from '../src/index.js'
import fetch from 'cross-fetch'
import crossFetch from 'cross-fetch'
import fetchCookie from 'fetch-cookie'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

const graphQLClient = new GraphQLClient(endpoint, { fetch: fetch })
/**
* Fetch with a cookie jar scoped to the client object.
*/
const fetch = fetchCookie(crossFetch)

const graphQLClient = new GraphQLClient(endpoint, { fetch })

const query = gql`
{
Expand All @@ -21,4 +27,4 @@ interface TData {
}

const data = await graphQLClient.rawRequest<TData>(query)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ interface TData {
}

const data = await graphQLClient.request<TData>(query)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
9 changes: 9 additions & 0 deletions examples/configuration-incremental-endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* If you want to change the endpoint after the GraphQLClient has been initialized, you can use the `setEndpoint()` function.
*/

import { GraphQLClient } from '../src/index.js'

const client = new GraphQLClient(`https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`)

client.setEndpoint(`https://api.graph.cool/simple/v2/cixos23120m0n0173veiiwrjr`)
16 changes: 16 additions & 0 deletions examples/configuration-incremental-request-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* If you want to set headers after the GraphQLClient has been initialized, you can use the `setHeader()` or `setHeaders()` functions.
*/

import { GraphQLClient } from '../src/index.js'

const client = new GraphQLClient(`https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`)

// Set a single header
client.setHeader(`authorization`, `Bearer MY_TOKEN`)

// Override all existing headers
client.setHeaders({
authorization: `Bearer MY_TOKEN`,
'x-another-header': `header_value`,
})
18 changes: 18 additions & 0 deletions examples/configuration-request-json-serializer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* If you want to use non-standard JSON types, you can use your own JSON serializer to replace `JSON.parse`/`JSON.stringify` used by the `GraphQLClient`.
* An original use case for this feature is `BigInt` support:
*/

import { gql, GraphQLClient } from '../src/index.js'
import JSONbig from 'json-bigint'

const jsonSerializer = JSONbig({ useNativeBigInt: true })
const graphQLClient = new GraphQLClient(`https://some-api`, { jsonSerializer })
const data = await graphQLClient.request<{ someBigInt: bigint }>(
gql`
{
someBigInt
}
`
)
console.log(typeof data.someBigInt) // if >MAX_SAFE_INTEGER then 'bigint' else 'number'
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* It is possible with `graphql-request` to use batching via the `batchRequests()` function.
* @see https://github.com/graphql/graphql-over-http/blob/main/rfcs/Batching.md
*/
import { batchRequests, gql } from '../src/index.js'

const endpoint = `https://api.spacex.land/graphql/`
Expand Down Expand Up @@ -53,4 +57,4 @@ const data = await batchRequests<[TData1, TData2, TData3]>(endpoint, [
{ document: query2 },
{ document: query3, variables: variables3 },
])
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ interface TData {
}

const data = await request<TData>(endpoint, query, variables)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
26 changes: 26 additions & 0 deletions examples/graphql-mutations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { gql, GraphQLClient } from '../src/index.js'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

const graphQLClient = new GraphQLClient(endpoint, {
headers: {
authorization: `Bearer MY_TOKEN`,
},
})

const mutation = gql`
mutation AddMovie($title: String!, $releaseDate: Int!) {
insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) {
title
releaseDate
}
}
`

const variables = {
title: `Inception`,
releaseDate: 2010,
}

const data = await graphQLClient.request(mutation, variables)
console.log(data)
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ interface TData {

try {
const data = await request<TData>(endpoint, query)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
} catch (error) {
console.error(JSON.stringify(error, undefined, 2))
console.error(error)
process.exit(1)
}
62 changes: 62 additions & 0 deletions examples/other-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* eslint-disable */

/**
* It's possible to use a middleware to pre-process any request or handle raw response.
*/

import { GraphQLClient } from '../src/index.js'
import type { RequestMiddleware } from '../src/types.js'

const endpoint = `https://api.spacex.land/graphql/`

const getAccessToken = () => Promise.resolve(`some special token here`)

{
/**
* Request middleware example (set actual auth token to each request):
*/

const requestMiddleware: RequestMiddleware = async (request) => {
const token = await getAccessToken()
return {
...request,
headers: { ...request.headers, 'x-auth-token': token },
}
}

const _client = new GraphQLClient(endpoint, { requestMiddleware })
}
{
/**
* It's also possible to use an async function as a request middleware. The resolved data will be passed to the request:
*/

const requestMiddleware: RequestMiddleware = async (request) => {
const token = await getAccessToken()
return {
...request,
headers: { ...request.headers, 'x-auth-token': token },
}
}

const _client = new GraphQLClient(endpoint, { requestMiddleware })
}
{
/**
* Response middleware example (log request trace id if error caused):
*/

// @ts-expect-error TODO export a response middleware type
const responseMiddleware = (response: Response<unknown>) => {
if (response.errors) {
const traceId = response.headers.get(`x-b3-trace-id`) || `unknown`
console.error(
`[${traceId}] Request error:
status ${response.status}
details: ${response.errors}`
)
}
}

const _client = new GraphQLClient(endpoint, { responseMiddleware })
}
23 changes: 23 additions & 0 deletions examples/other-package-commonjs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* eslint-disable */

const { request, gql } = require(`graphql-request`)

main()

async function main() {
const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

const query = gql`
{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}
`

const data = await request(endpoint, query)
console.log(data)
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ interface TData {
}

const data = await graphQLClient.request<TData>(query)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
59 changes: 59 additions & 0 deletions examples/request-cancellation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* It is possible to cancel a request using an `AbortController` signal.
*/

import { gql, GraphQLClient } from '../src/index.js'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

/**
* You can define the `signal` in the `GraphQLClient` constructor:
*/

{
const abortController = new AbortController()

const client = new GraphQLClient(endpoint, {
signal: abortController.signal,
})

// todo
// eslint-disable-next-line
client.request(gql`
{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}
`)

abortController.abort()
}

/**
* You can also set the signal per request (this will override an existing GraphQLClient signal):
*/

{
const abortController = new AbortController()

const client = new GraphQLClient(endpoint)
const document = gql`
{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}
`
const _requesting = client.request({
document,
signal: abortController.signal,
})
abortController.abort()
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import { gql, GraphQLClient } from '../src/index.js'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`

const graphQLClient = new GraphQLClient(endpoint, {
const client = new GraphQLClient(`https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`, {
headers: {
authorization: `Bearer MY_TOKEN`,
},
Expand All @@ -25,5 +23,5 @@ interface TData {
Movie: { releaseDate: string; actors: Array<{ name: string }> }
}

const data = await graphQLClient.rawRequest<TData>(query)
console.log(JSON.stringify(data, undefined, 2))
const data = await client.rawRequest<TData>(query)
console.log(data)
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* The `request` method will return the `data` or `errors` key from the response.
* If you need to access the `extensions` key you can use the `rawRequest` method:
*/

import { gql, rawRequest } from '../src/index.js'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`
Expand All @@ -18,4 +23,4 @@ interface TData {
}

const { data, errors, extensions, headers, status } = await rawRequest<TData>(endpoint, query)
console.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2))
console.log({ data, errors, extensions, headers, status })
21 changes: 21 additions & 0 deletions examples/request-headers-dynamic-per-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* It's possible to recalculate the global client headers dynamically before each request.
* To do that, pass a function that returns the headers to the `headers` property when creating a new `GraphQLClient`.
*/

import { gql, GraphQLClient } from '../src/index.js'

const client = new GraphQLClient(`https://some-api`, {
headers: () => ({ 'X-Sent-At-Time': Date.now().toString() }),
})

const query = gql`
query getCars {
cars {
name
}
}
`
// Function saved in the client runs and calculates fresh headers before each request
const data = await client.request(query)
console.log(data)
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* It is possible to pass custom headers for each request. `request()` and `rawRequest()` accept a header object as the third parameter
*/

import { gql, GraphQLClient } from '../src/index.js'

const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr`
Expand Down Expand Up @@ -29,4 +33,4 @@ interface TData {
}

const data = await client.request<TData>(query, {}, requestHeaders)
console.log(JSON.stringify(data, undefined, 2))
console.log(data)
Loading

0 comments on commit 6b3396b

Please sign in to comment.