From cc86c347640302434a950f3987f7285c29796430 Mon Sep 17 00:00:00 2001 From: Jason Kuhrt Date: Sat, 17 Feb 2024 18:23:38 -0500 Subject: [PATCH] refactor: use dprint instead of prettier (#677) --- .eslintrc | 4 +- .vscode/extensions.json | 6 +- README.md | 6 +- dprint.json | 19 ++++ .../configuration-fetch-custom-function.ts | 2 +- .../configuration-request-json-serializer.ts | 2 +- examples/typescript-typed-document-node.ts | 2 +- package.json | 15 ++- pnpm-lock.yaml | 92 ++++++++++++++---- src/legacy/classes/ClientError.ts | 10 +- src/legacy/classes/GraphQLClient.ts | 95 ++++++++++++++----- src/legacy/functions/batchRequests.ts | 13 ++- src/legacy/functions/rawRequest.ts | 26 ++--- src/legacy/functions/request.ts | 37 ++++---- src/legacy/helpers/runRequest.ts | 67 +++++++------ src/legacy/helpers/types.ts | 53 ++++++----- src/legacy/lib/graphql.ts | 10 +- src/lib/prelude.ts | 16 ++-- tests/batching.test.ts | 2 +- tests/custom-fetch.test.ts | 2 +- tests/document-node.test.ts | 4 +- tests/endpoint.test.ts | 2 +- tests/errorPolicy.test.ts | 2 +- tests/fetch.test.ts | 2 +- tests/general.test.ts | 4 +- tests/gql.test.ts | 4 +- tests/headers.test.ts | 2 +- tests/httpMethod.test.ts | 2 +- tests/json-serializer.test.ts | 22 ++--- tests/signal.test.ts | 2 +- tests/typed-document-node.test.ts | 4 +- tsconfig.json | 4 +- 32 files changed, 322 insertions(+), 211 deletions(-) create mode 100644 dprint.json diff --git a/.eslintrc b/.eslintrc index 3115e9461..8c46a9fa2 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,5 +2,7 @@ "root": true, "extends": ["prisma"], "overrides": [], - "rules": {} + "rules": { + "simple-import-sort/imports": "off" + } } diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 4df8334c5..765e8bb87 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,7 @@ { - "recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint", "orta.vscode-twoslash-queries"] + "recommendations": [ + "dprint.dprint", + "dbaeumer.vscode-eslint", + "orta.vscode-twoslash-queries" + ] } diff --git a/README.md b/README.md index 4e4da066d..81ed6a157 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ npm add graphql-request graphql Send a GraphQL document using a static request function: ```js -import { request, gql } from 'graphql-request' +import { gql, request } from 'graphql-request' const document = gql` { @@ -73,7 +73,7 @@ await request({ A class is available for constructing your own instances: ```js -import { GraphQLClient, gql } from 'graphql-request' +import { gql, GraphQLClient } from 'graphql-request' const document = gql` { @@ -185,7 +185,7 @@ In [this issue](https://github.com/jasonkuhrt/graphql-request/issues/500) we dec #### Do I need to wrap my GraphQL documents inside the `gql` template exported by `graphql-request`? -No. It is there for convenience so that you can get the tooling support like prettier formatting and IDE syntax highlighting. You can use `gql` from `graphql-tag` if you need it for some reason too. +No. 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. #### What sets `graphql-request` apart from other clients like Apollo, Relay, etc.? diff --git a/dprint.json b/dprint.json new file mode 100644 index 000000000..72af1d534 --- /dev/null +++ b/dprint.json @@ -0,0 +1,19 @@ +{ + "typescript": { + "quoteStyle": "preferSingle", + "semiColons": "asi" + }, + "json": { + }, + "markdown": { + }, + "excludes": [ + "**/node_modules", + "**/*-lock.json" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.89.1.wasm", + "https://plugins.dprint.dev/json-0.19.1.wasm", + "https://plugins.dprint.dev/markdown-0.16.3.wasm" + ] +} diff --git a/examples/configuration-fetch-custom-function.ts b/examples/configuration-fetch-custom-function.ts index fffaa5455..59f97fd97 100644 --- a/examples/configuration-fetch-custom-function.ts +++ b/examples/configuration-fetch-custom-function.ts @@ -1,5 +1,5 @@ -import { gql, GraphQLClient } from '../src/entrypoints/main.js' import fetchCookie from 'fetch-cookie' +import { gql, GraphQLClient } from '../src/entrypoints/main.js' const endpoint = `https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr` diff --git a/examples/configuration-request-json-serializer.ts b/examples/configuration-request-json-serializer.ts index f699b0137..a7300b6ed 100644 --- a/examples/configuration-request-json-serializer.ts +++ b/examples/configuration-request-json-serializer.ts @@ -3,8 +3,8 @@ * An original use case for this feature is `BigInt` support: */ -import { gql, GraphQLClient } from '../src/entrypoints/main.js' import JSONbig from 'json-bigint' +import { gql, GraphQLClient } from '../src/entrypoints/main.js' const jsonSerializer = JSONbig({ useNativeBigInt: true }) const graphQLClient = new GraphQLClient(`https://some-api`, { jsonSerializer }) diff --git a/examples/typescript-typed-document-node.ts b/examples/typescript-typed-document-node.ts index a38331218..aae922903 100644 --- a/examples/typescript-typed-document-node.ts +++ b/examples/typescript-typed-document-node.ts @@ -1,6 +1,6 @@ -import { gql, GraphQLClient, request } from '../src/entrypoints/main.js' import type { TypedDocumentNode } from '@graphql-typed-document-node/core' import { parse } from 'graphql' +import { gql, GraphQLClient, request } from '../src/entrypoints/main.js' { const endpoint = `https://graphql-yoga.com/api/graphql` diff --git a/package.json b/package.json index 1cfcef4eb..ceb6140b6 100644 --- a/package.json +++ b/package.json @@ -37,14 +37,14 @@ "homepage": "https://github.com/jasonkuhrt/graphql-request", "scripts": { "dev": "rm -rf dist && tsc --watch", - "format": "pnpm build:docs && prettier --write .", + "format": "pnpm build:docs && dprint fmt", "lint": "eslint . --ext .ts,.tsx --fix", "check": "pnpm check:types && pnpm check:format && pnpm check:lint", "check:types": "pnpm tsc --noEmit", - "check:format": "prettier --check . && pnpm build:docs && git diff --exit-code README.md", + "check:format": "dprint check && pnpm build:docs && git diff --exit-code README.md", "check:lint": "eslint . --ext .ts,.tsx --max-warnings 0", "prepublishOnly": "pnpm build", - "build:docs": "doctoc README.md --notitle && prettier --write README.md", + "build:docs": "doctoc README.md --notitle && dprint fmt README.md", "build": "pnpm clean && pnpm tsc --project tsconfig.build.json", "clean": "tsc --build --clean && rm -rf build", "test": "vitest", @@ -54,14 +54,14 @@ "release:pr": "dripip pr" }, "dependencies": { - "@graphql-typed-document-node/core": "^3.2.0" + "@graphql-typed-document-node/core": "^3.2.0", + "dprint": "^0.45.0" }, "peerDependencies": { "graphql": "14 - 16" }, "devDependencies": { "@graphql-tools/schema": "^10.0.2", - "@prisma-labs/prettier-config": "^0.1.0", "@tsconfig/node16": "^16.1.1", "@types/body-parser": "^1.19.5", "@types/express": "^4.17.21", @@ -75,7 +75,6 @@ "doctoc": "^2.2.1", "dripip": "^0.10.0", "eslint": "^8.56.0", - "eslint-config-prettier": "^9.1.0", "eslint-config-prisma": "^0.2.0", "eslint-plugin-deprecation": "^2.0.0", "eslint-plugin-only-warn": "^1.1.0", @@ -90,12 +89,10 @@ "graphql-ws": "^5.14.3", "happy-dom": "^13.3.1", "json-bigint": "^1.0.0", - "prettier": "^3.2.4", "tsx": "^4.7.0", "type-fest": "^4.10.1", "typescript": "^5.3.3", "vitest": "^1.2.1", "ws": "^8.16.0" - }, - "prettier": "@prisma-labs/prettier-config" + } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dd8edf361..e6d377f76 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,14 +8,14 @@ dependencies: '@graphql-typed-document-node/core': specifier: ^3.2.0 version: 3.2.0(graphql@16.8.1) + dprint: + specifier: ^0.45.0 + version: 0.45.0 devDependencies: '@graphql-tools/schema': specifier: ^10.0.2 version: 10.0.2(graphql@16.8.1) - '@prisma-labs/prettier-config': - specifier: ^0.1.0 - version: 0.1.0 '@tsconfig/node16': specifier: ^16.1.1 version: 16.1.1 @@ -55,9 +55,6 @@ devDependencies: eslint: specifier: ^8.56.0 version: 8.56.0 - eslint-config-prettier: - specifier: ^9.1.0 - version: 9.1.0(eslint@8.56.0) eslint-config-prisma: specifier: ^0.2.0 version: 0.2.0(@typescript-eslint/eslint-plugin@7.0.1)(@typescript-eslint/parser@7.0.1)(eslint-plugin-deprecation@2.0.0)(eslint-plugin-only-warn@1.1.0)(eslint-plugin-prefer-arrow@1.2.3)(eslint-plugin-simple-import-sort@12.0.0)(eslint-plugin-tsdoc@0.2.17)(eslint@8.56.0) @@ -100,9 +97,6 @@ devDependencies: json-bigint: specifier: ^1.0.0 version: 1.0.0 - prettier: - specifier: ^3.2.4 - version: 3.2.4 tsx: specifier: ^4.7.0 version: 4.7.0 @@ -258,6 +252,62 @@ packages: xss: 1.0.14 dev: true + /@dprint/darwin-arm64@0.45.0: + resolution: {integrity: sha512-pkSSmixIKXr5t32bhXIUbpIBm8F8uhsJcUUvfkFNsRbQvNwRp71ribZpE8dKl0ZFOlAFeWD6WLE8smp/QtiGUA==} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: false + optional: true + + /@dprint/darwin-x64@0.45.0: + resolution: {integrity: sha512-PHcXSrRO53KH9N+YPbPtr40NnDo2t7hO7KLMfl2ktRNLjrmKg6F8XDDsr2C7Z11k3jyEEU2Jq8hhpaKHwNapmQ==} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: false + optional: true + + /@dprint/linux-arm64-glibc@0.45.0: + resolution: {integrity: sha512-NgIpvZHpiQaY4DxSygxknxBtvKE2KLK9dEbUNKNE098yTHhGq7ouPsoM7RtsO34RHJ3tEZLLJEuBHn20XP8LMg==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: false + optional: true + + /@dprint/linux-arm64-musl@0.45.0: + resolution: {integrity: sha512-Y8p+FC0RNyKCGQjy99Uh1LSPrlQtUTvo4brdvU1THF3pyWu6Bg1p6NiP5a6SjE/6t9CMKZJz39zPreQtnDkSDA==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: false + optional: true + + /@dprint/linux-x64-glibc@0.45.0: + resolution: {integrity: sha512-u03NCZIpJhE5gIl9Q7jNL4sOPBFd/8BLVBiuLoLtbiTZQ+NNudHKgGNATJBU67q1MKpqKnt8/gQm139cJkHhrw==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: false + optional: true + + /@dprint/linux-x64-musl@0.45.0: + resolution: {integrity: sha512-DQN8LPtxismkeU1X+sQywa80kWwCBcpQh9fXoJcvTEHrgzHBqbG2SEsUZpM12oKEua1KE/iBh+vgZ+4I3TdI2A==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: false + optional: true + + /@dprint/win32-x64@0.45.0: + resolution: {integrity: sha512-aZHIWG2jIlEp4BER1QG6YYqPd6TxT9S77AeUkWJixNiMEo+33mPRVCBcugRWI/WJWveX8yWFVXkToORtnSFeEA==} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: false + optional: true + /@esbuild/aix-ppc64@0.19.12: resolution: {integrity: sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA==} engines: {node: '>=12'} @@ -964,10 +1014,6 @@ packages: '@octokit/openapi-types': 12.11.0 dev: true - /@prisma-labs/prettier-config@0.1.0: - resolution: {integrity: sha512-P0h2y+gnIxFP2HdsTYSYHWmabGBlxyVjnUepsrRe8gAF36mxOonGsbsQmKt/Q9H9CMjrSkFoDe5F5HLi2iW5/Q==} - dev: true - /@protobufjs/aspromise@1.1.2: resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} dev: true @@ -2174,6 +2220,20 @@ packages: domhandler: 4.3.1 dev: true + /dprint@0.45.0: + resolution: {integrity: sha512-3444h7V47XoA16qgIWjw3CV/Eo/rQbT/XTGlbJ/6vJ+apQyuo0+M3Ai0GS3wu7X9HBUDcA0zIHA3mOxWNz6toA==} + hasBin: true + requiresBuild: true + optionalDependencies: + '@dprint/darwin-arm64': 0.45.0 + '@dprint/darwin-x64': 0.45.0 + '@dprint/linux-arm64-glibc': 0.45.0 + '@dprint/linux-arm64-musl': 0.45.0 + '@dprint/linux-x64-glibc': 0.45.0 + '@dprint/linux-x64-musl': 0.45.0 + '@dprint/win32-x64': 0.45.0 + dev: false + /dripip@0.10.0: resolution: {integrity: sha512-FaHkW6uXAa57pJwz+SRxTvTDiybSH9w4PGWXkheoIPNs4HcHM688rfsKzvedoaLvQul4UaAoRr+2CHc7V25biA==} hasBin: true @@ -3686,12 +3746,6 @@ packages: engines: {node: '>= 0.8.0'} dev: true - /prettier@3.2.4: - resolution: {integrity: sha512-FWu1oLHKCrtpO1ypU6J0SbK2d9Ckwysq6bHj/uaCP26DxrPpppCLQRGVuqAxSTvhF00AcvDRyYrLNW7ocBhFFQ==} - engines: {node: '>=14'} - hasBin: true - dev: true - /pretty-format@29.7.0: resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} diff --git a/src/legacy/classes/ClientError.ts b/src/legacy/classes/ClientError.ts index f879d4868..8e27d1202 100644 --- a/src/legacy/classes/ClientError.ts +++ b/src/legacy/classes/ClientError.ts @@ -5,10 +5,12 @@ export class ClientError extends Error { public request: GraphQLRequestContext constructor(response: GraphQLResponse, request: GraphQLRequestContext) { - const message = `${ClientError.extractMessage(response)}: ${JSON.stringify({ - response, - request, - })}` + const message = `${ClientError.extractMessage(response)}: ${ + JSON.stringify({ + response, + request, + }) + }` super(message) diff --git a/src/legacy/classes/GraphQLClient.ts b/src/legacy/classes/GraphQLClient.ts index 112dfff6d..fc83974c5 100644 --- a/src/legacy/classes/GraphQLClient.ts +++ b/src/legacy/classes/GraphQLClient.ts @@ -1,3 +1,4 @@ +import type { TypedDocumentNode } from '@graphql-typed-document-node/core' import { callOrIdentity, HeadersInitToPlainObject } from '../../lib/prelude.js' import type { BatchRequestDocument, BatchRequestsOptions, BatchResult } from '../functions/batchRequests.js' import { parseBatchRequestArgs } from '../functions/batchRequests.js' @@ -12,7 +13,6 @@ import { type RequestConfig, type Variables, } from '../helpers/types.js' -import type { TypedDocumentNode } from '@graphql-typed-document-node/core' /** * GraphQL Client. @@ -26,11 +26,18 @@ export class GraphQLClient { /** * Send a GraphQL query to the server. */ - rawRequest: RawRequestMethod = async ( + rawRequest: RawRequestMethod = async < + T, + $Variables extends Variables = Variables, + >( ...args: RawRequestMethodArgs<$Variables> ): Promise> => { const [queryOrOptions, variables, requestHeaders] = args - const rawRequestOptions = parseRawRequestArgs<$Variables>(queryOrOptions, variables, requestHeaders) + const rawRequestOptions = parseRawRequestArgs<$Variables>( + queryOrOptions, + variables, + requestHeaders, + ) const { headers, fetch = globalThis.fetch, @@ -45,7 +52,10 @@ export class GraphQLClient { fetchOptions.signal = rawRequestOptions.signal } - const document = analyzeDocument(rawRequestOptions.query, excludeOperationName) + const document = analyzeDocument( + rawRequestOptions.query, + excludeOperationName, + ) const response = await runRequest({ url, @@ -82,13 +92,22 @@ export class GraphQLClient { document: RequestDocument | TypedDocumentNode, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs ): Promise - async request(options: RequestOptions): Promise async request( - documentOrOptions: RequestDocument | TypedDocumentNode | RequestOptions, + options: RequestOptions, + ): Promise + async request( + documentOrOptions: + | RequestDocument + | TypedDocumentNode + | RequestOptions, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs ): Promise { const [variables, requestHeaders] = variablesAndRequestHeaders - const requestOptions = parseRequestArgs(documentOrOptions, variables, requestHeaders) + const requestOptions = parseRequestArgs( + documentOrOptions, + variables, + requestHeaders, + ) const { headers, @@ -104,7 +123,10 @@ export class GraphQLClient { fetchOptions.signal = requestOptions.signal } - const analyzedDocument = analyzeDocument(requestOptions.document, excludeOperationName) + const analyzedDocument = analyzeDocument( + requestOptions.document, + excludeOperationName, + ) const response = await runRequest({ url, @@ -137,13 +159,30 @@ export class GraphQLClient { /** * Send GraphQL documents in batch to the server. */ - // prettier-ignore - async batchRequests<$BatchResult extends BatchResult, $Variables extends Variables = Variables>(documents: BatchRequestDocument<$Variables>[], requestHeaders?: HeadersInit): Promise<$BatchResult> - // prettier-ignore - async batchRequests<$BatchResult extends BatchResult, $Variables extends Variables = Variables>(options: BatchRequestsOptions<$Variables>): Promise<$BatchResult> - // prettier-ignore - async batchRequests<$BatchResult extends BatchResult, $Variables extends Variables = Variables>(documentsOrOptions: BatchRequestDocument<$Variables>[] | BatchRequestsOptions<$Variables>, requestHeaders?: HeadersInit): Promise<$BatchResult> { - const batchRequestOptions = parseBatchRequestArgs<$Variables>(documentsOrOptions, requestHeaders) + async batchRequests< + $BatchResult extends BatchResult, + $Variables extends Variables = Variables, + >( + documents: BatchRequestDocument<$Variables>[], + requestHeaders?: HeadersInit, + ): Promise<$BatchResult> + async batchRequests< + $BatchResult extends BatchResult, + $Variables extends Variables = Variables, + >(options: BatchRequestsOptions<$Variables>): Promise<$BatchResult> + async batchRequests< + $BatchResult extends BatchResult, + $Variables extends Variables = Variables, + >( + documentsOrOptions: + | BatchRequestDocument<$Variables>[] + | BatchRequestsOptions<$Variables>, + requestHeaders?: HeadersInit, + ): Promise<$BatchResult> { + const batchRequestOptions = parseBatchRequestArgs<$Variables>( + documentsOrOptions, + requestHeaders, + ) const { headers, excludeOperationName, ...fetchOptions } = this.requestConfig if (batchRequestOptions.signal !== undefined) { @@ -151,16 +190,18 @@ export class GraphQLClient { } const analyzedDocuments = batchRequestOptions.documents.map( - ({ document }) => analyzeDocument(document, excludeOperationName) + ({ document }) => analyzeDocument(document, excludeOperationName), ) const expressions = analyzedDocuments.map(({ expression }) => expression) const hasMutations = analyzedDocuments.some(({ isMutation }) => isMutation) - const variables = batchRequestOptions.documents.map(({ variables }) => variables) + const variables = batchRequestOptions.documents.map( + ({ variables }) => variables, + ) - const response= await runRequest({ + const response = await runRequest({ url: this.url, request: { - _tag:`Batch`, + _tag: `Batch`, operationName: undefined, query: expressions, hasMutations, @@ -175,7 +216,7 @@ export class GraphQLClient { fetchOptions, middleware: this.requestConfig.requestMiddleware, }) - + if (this.requestConfig.responseMiddleware) { this.requestConfig.responseMiddleware(response) } @@ -200,7 +241,7 @@ export class GraphQLClient { if (headers) { // todo what if headers is in nested array form... ? - //@ts-expect-error todo + // @ts-expect-error todo headers[key] = value } else { this.requestConfig.headers = { [key]: value } @@ -218,13 +259,17 @@ export class GraphQLClient { } } -// prettier-ignore interface RawRequestMethod { - (query: string, variables?: V, requestHeaders?: HeadersInit): Promise> - (options: RawRequestOptions): Promise> + ( + query: string, + variables?: V, + requestHeaders?: HeadersInit, + ): Promise> + (options: RawRequestOptions): Promise< + GraphQLClientResponse + > } -// prettier-ignore type RawRequestMethodArgs = | [query: string, variables?: V, requestHeaders?: HeadersInit] | [RawRequestOptions] diff --git a/src/legacy/functions/batchRequests.ts b/src/legacy/functions/batchRequests.ts index dfa099f8c..3ad48e150 100644 --- a/src/legacy/functions/batchRequests.ts +++ b/src/legacy/functions/batchRequests.ts @@ -12,8 +12,7 @@ export interface BatchRequestsOptions { signal?: RequestInit['signal'] } -export interface BatchRequestsExtendedOptions - extends BatchRequestsOptions { +export interface BatchRequestsExtendedOptions extends BatchRequestsOptions { url: string } @@ -74,7 +73,7 @@ export const parseBatchRequestsArgsExtended = (args: BatchRequestsArgs): BatchRe } } -// prettier-ignore +// dprint-ignore interface BatchRequests { (url: string, documents: BatchRequestDocument[], requestHeaders?: HeadersInit): Promise (options: BatchRequestsExtendedOptions): Promise @@ -93,8 +92,8 @@ export const parseBatchRequestArgs = ( return (documentsOrOptions as BatchRequestsOptions).documents ? (documentsOrOptions as BatchRequestsOptions) : { - documents: documentsOrOptions as BatchRequestDocument[], - requestHeaders: requestHeaders, - signal: undefined, - } + documents: documentsOrOptions as BatchRequestDocument[], + requestHeaders: requestHeaders, + signal: undefined, + } } diff --git a/src/legacy/functions/rawRequest.ts b/src/legacy/functions/rawRequest.ts index 1684475e2..07f94c5c8 100644 --- a/src/legacy/functions/rawRequest.ts +++ b/src/legacy/functions/rawRequest.ts @@ -20,13 +20,13 @@ export const rawRequest: RawRequest = async ( }) } -// prettier-ignore +// dprint-ignore interface RawRequest { (url: string, query: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs): Promise> (options: RawRequestExtendedOptions): Promise> } -// prettier-ignore +// dprint-ignore type RawRequestArgs = | [options: RawRequestExtendedOptions, query?: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs] | [url: string, query?: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs] @@ -39,12 +39,12 @@ export const parseRawRequestExtendedArgs = ( const [variables, requestHeaders] = variablesAndRequestHeaders return typeof urlOrOptions === `string` ? ({ - url: urlOrOptions, - query: query as string, - variables, - requestHeaders, - signal: undefined, - } as unknown as RawRequestExtendedOptions) + url: urlOrOptions, + query: query as string, + variables, + requestHeaders, + signal: undefined, + } as unknown as RawRequestExtendedOptions) : urlOrOptions } @@ -60,9 +60,9 @@ export const parseRawRequestArgs = ( return (queryOrOptions as RawRequestOptions).query ? (queryOrOptions as RawRequestOptions) : ({ - query: queryOrOptions as string, - variables: variables, - requestHeaders: requestHeaders, - signal: undefined, - } as unknown as RawRequestOptions) + query: queryOrOptions as string, + variables: variables, + requestHeaders: requestHeaders, + signal: undefined, + } as unknown as RawRequestOptions) } diff --git a/src/legacy/functions/request.ts b/src/legacy/functions/request.ts index d166f2618..43a8566f2 100644 --- a/src/legacy/functions/request.ts +++ b/src/legacy/functions/request.ts @@ -1,11 +1,6 @@ -import { GraphQLClient } from '../classes/GraphQLClient.js' -import type { - RequestDocument, - RequestOptions, - Variables, - VariablesAndRequestHeadersArgs, -} from '../helpers/types.js' import type { TypedDocumentNode } from '@graphql-typed-document-node/core' +import { GraphQLClient } from '../classes/GraphQLClient.js' +import type { RequestDocument, RequestOptions, Variables, VariablesAndRequestHeadersArgs } from '../helpers/types.js' /** * Send a GraphQL Document to the GraphQL server for execution. @@ -44,11 +39,11 @@ import type { TypedDocumentNode } from '@graphql-typed-document-node/core' // REMARKS: In order to have autocomplete for options work make it the first overload. If not // then autocomplete will instead show the various methods for a string, which is not what we want. -// prettier-ignore +// dprint-ignore export async function request(options: RequestExtendedOptions): Promise -// prettier-ignore +// dprint-ignore export async function request(url: string, document: RequestDocument | TypedDocumentNode, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs): Promise -// prettier-ignore +// dprint-ignore // eslint-disable-next-line export async function request(urlOrOptions: string | RequestExtendedOptions, document?: RequestDocument | TypedDocumentNode, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs): Promise { const requestOptions = parseRequestExtendedArgs(urlOrOptions, document, ...variablesAndRequestHeaders) @@ -66,11 +61,11 @@ export const parseRequestArgs = ( return (documentOrOptions as RequestOptions).document ? (documentOrOptions as RequestOptions) : ({ - document: documentOrOptions as RequestDocument, - variables: variables, - requestHeaders: requestHeaders, - signal: undefined, - } as unknown as RequestOptions) + document: documentOrOptions as RequestDocument, + variables: variables, + requestHeaders: requestHeaders, + signal: undefined, + } as unknown as RequestOptions) } export type RequestExtendedOptions = { @@ -85,11 +80,11 @@ export const parseRequestExtendedArgs = ( const [variables, requestHeaders] = variablesAndRequestHeaders return typeof urlOrOptions === `string` ? ({ - url: urlOrOptions, - document: document as RequestDocument, - variables, - requestHeaders, - signal: undefined, - } as unknown as RequestExtendedOptions) + url: urlOrOptions, + document: document as RequestDocument, + variables, + requestHeaders, + signal: undefined, + } as unknown as RequestExtendedOptions) : urlOrOptions } diff --git a/src/legacy/helpers/runRequest.ts b/src/legacy/helpers/runRequest.ts index a785b44ed..75a220e67 100644 --- a/src/legacy/helpers/runRequest.ts +++ b/src/legacy/helpers/runRequest.ts @@ -34,21 +34,21 @@ interface Input { middleware?: RequestMiddleware request: | { - _tag: 'Single' - variables?: Variables - document: { - expression: string - isMutation: boolean - operationName?: string - } + _tag: 'Single' + variables?: Variables + document: { + expression: string + isMutation: boolean + operationName?: string } + } | { - _tag: 'Batch' - query: string[] - operationName?: undefined - hasMutations: boolean - variables?: BatchVariables - } + _tag: 'Batch' + query: string[] + operationName?: undefined + hasMutations: boolean + variables?: BatchVariables + } } // @ts-expect-error todo @@ -56,14 +56,13 @@ export const runRequest = async (input: Input): Promise (executionResult: GraphQLExecutionResultSingle) => { - return { - extensions: executionResult.extensions, - data: executionResult.data, - errors: $params.fetchOptions.errorPolicy === `all` ? executionResult.errors : undefined, - } +const executionResultClientResponseFields = ($params: Input) => (executionResult: GraphQLExecutionResultSingle) => { + return { + extensions: executionResult.extensions, + data: executionResult.data, + errors: $params.fetchOptions.errorPolicy === `all` ? executionResult.errors : undefined, } +} const parseResultFromResponse = async (response: Response, jsonSerializer: JsonSerializer) => { const contentType = response.headers.get(CONTENT_TYPE_HEADER) diff --git a/src/legacy/helpers/types.ts b/src/legacy/helpers/types.ts index 2acd61c5d..949530222 100644 --- a/src/legacy/helpers/types.ts +++ b/src/legacy/helpers/types.ts @@ -1,8 +1,8 @@ -import type { MaybeLazy, RemoveIndex } from '../../lib/prelude.js' -import type { ClientError } from '../classes/ClientError.js' import type { TypedDocumentNode } from '@graphql-typed-document-node/core' import type { GraphQLError } from 'graphql/error/GraphQLError.js' import type { DocumentNode } from 'graphql/language/ast.js' +import type { MaybeLazy, RemoveIndex } from '../../lib/prelude.js' +import type { ClientError } from '../classes/ClientError.js' export type Fetch = typeof fetch @@ -70,30 +70,33 @@ export interface RequestConfig extends Omit, excludeOperationName?: boolean } -export type RawRequestOptions = { - query: string - requestHeaders?: HeadersInit - signal?: RequestInit['signal'] -} & (V extends Record - ? { variables?: V } - : keyof RemoveIndex extends never - ? { variables?: V } +export type RawRequestOptions = + & { + query: string + requestHeaders?: HeadersInit + signal?: RequestInit['signal'] + } + & (V extends Record ? { variables?: V } + : keyof RemoveIndex extends never ? { variables?: V } : { variables: V }) -export type RequestOptions = { - document: RequestDocument | TypedDocumentNode - requestHeaders?: HeadersInit - signal?: RequestInit['signal'] -} & (V extends Record - ? { variables?: V } - : keyof RemoveIndex extends never - ? { variables?: V } +export type RequestOptions = + & { + document: RequestDocument | TypedDocumentNode + requestHeaders?: HeadersInit + signal?: RequestInit['signal'] + } + & (V extends Record ? { variables?: V } + : keyof RemoveIndex extends never ? { variables?: V } : { variables: V }) -export type ResponseMiddleware = (response: GraphQLClientResponse | ClientError | Error) => void +export type ResponseMiddleware = ( + response: GraphQLClientResponse | ClientError | Error, +) => void -// prettier-ignore -export type RequestMiddleware = (request: RequestExtendedInit) => RequestExtendedInit | Promise +export type RequestMiddleware = ( + request: RequestExtendedInit, +) => RequestExtendedInit | Promise type RequestExtendedInit = RequestInit & { url: string @@ -101,10 +104,8 @@ type RequestExtendedInit = RequestInit & { variables?: V } -// prettier-ignore -export type VariablesAndRequestHeadersArgs = - V extends Record // do we have explicitly no variables allowed? - ? [variables?: V, requestHeaders?: HeadersInit] +export type VariablesAndRequestHeadersArgs = V extends Record // do we have explicitly no variables allowed? + ? [variables?: V, requestHeaders?: HeadersInit] : keyof RemoveIndex extends never // do we get an empty variables object? ? [variables?: V, requestHeaders?: HeadersInit] - : [variables: V, requestHeaders?: HeadersInit] + : [variables: V, requestHeaders?: HeadersInit] diff --git a/src/legacy/lib/graphql.ts b/src/legacy/lib/graphql.ts index 7362c649e..ab0451123 100644 --- a/src/legacy/lib/graphql.ts +++ b/src/legacy/lib/graphql.ts @@ -1,6 +1,6 @@ +import { Kind } from 'graphql' import { CONTENT_TYPE_GQL, CONTENT_TYPE_JSON } from '../../lib/http.js' import { isPlainObject } from '../../lib/prelude.js' -import { Kind } from 'graphql' /** * Refactored imports from `graphql` to be more specific, this helps import only the required files (100KiB) * instead of the entire package (greater than 500KiB) where tree-shaking is not supported. @@ -98,9 +98,9 @@ export const isExecutionResultHaveErrors = (result: GraphQLExecutionResultSingle export const isOperationDefinitionNode = (definition: unknown): definition is OperationDefinitionNode => { return ( - typeof definition === `object` && - definition !== null && - `kind` in definition && - definition.kind === Kind.OPERATION_DEFINITION + typeof definition === `object` + && definition !== null + && `kind` in definition + && definition.kind === Kind.OPERATION_DEFINITION ) } diff --git a/src/lib/prelude.ts b/src/lib/prelude.ts index 65f59c9e7..18caa5b50 100644 --- a/src/lib/prelude.ts +++ b/src/lib/prelude.ts @@ -65,14 +65,14 @@ export const errorFromMaybeError = (maybeError: unknown): Error => { export const isPromiseLikeValue = (value: unknown): value is Promise => { return ( - typeof value === `object` && - value !== null && - `then` in value && - typeof value.then === `function` && - `catch` in value && - typeof value.catch === `function` && - `finally` in value && - typeof value.finally === `function` + typeof value === `object` + && value !== null + && `then` in value + && typeof value.then === `function` + && `catch` in value + && typeof value.catch === `function` + && `finally` in value + && typeof value.finally === `function` ) } diff --git a/tests/batching.test.ts b/tests/batching.test.ts index c7aa03732..0ddf5719d 100644 --- a/tests/batching.test.ts +++ b/tests/batching.test.ts @@ -1,7 +1,7 @@ +import { expect, test } from 'vitest' import { batchRequests } from '../src/entrypoints/main.js' import type { MockSpecBatch } from './__helpers.js' import { errors, setupMockServer } from './__helpers.js' -import { expect, test } from 'vitest' const mockServer = setupMockServer() diff --git a/tests/custom-fetch.test.ts b/tests/custom-fetch.test.ts index 36343d84a..e9da5481f 100644 --- a/tests/custom-fetch.test.ts +++ b/tests/custom-fetch.test.ts @@ -1,6 +1,6 @@ +import { expect, test } from 'vitest' import { GraphQLClient } from '../src/entrypoints/main.js' import { setupMockServer } from './__helpers.js' -import { expect, test } from 'vitest' const ctx = setupMockServer() diff --git a/tests/document-node.test.ts b/tests/document-node.test.ts index a2a98033f..d65c46cd4 100644 --- a/tests/document-node.test.ts +++ b/tests/document-node.test.ts @@ -1,7 +1,7 @@ -import { request } from '../src/entrypoints/main.js' -import { setupMockServer } from './__helpers.js' import { gql } from 'graphql-tag' import { expect, it } from 'vitest' +import { request } from '../src/entrypoints/main.js' +import { setupMockServer } from './__helpers.js' const ctx = setupMockServer() diff --git a/tests/endpoint.test.ts b/tests/endpoint.test.ts index f4830904a..b04110edf 100644 --- a/tests/endpoint.test.ts +++ b/tests/endpoint.test.ts @@ -1,6 +1,6 @@ +import { describe, expect, test } from 'vitest' import { GraphQLClient } from '../src/entrypoints/main.js' import { setupMockServer } from './__helpers.js' -import { describe, expect, test } from 'vitest' const ctx_0 = setupMockServer() const ctx_1 = setupMockServer() diff --git a/tests/errorPolicy.test.ts b/tests/errorPolicy.test.ts index bbf687131..8f8336c23 100644 --- a/tests/errorPolicy.test.ts +++ b/tests/errorPolicy.test.ts @@ -1,6 +1,6 @@ +import { describe, expect, test } from 'vitest' import { GraphQLClient } from '../src/entrypoints/main.js' import { errors, setupMockServer } from './__helpers.js' -import { describe, expect, test } from 'vitest' const ctx = setupMockServer() diff --git a/tests/fetch.test.ts b/tests/fetch.test.ts index e1e9ccd65..db5aab391 100644 --- a/tests/fetch.test.ts +++ b/tests/fetch.test.ts @@ -1,5 +1,5 @@ -import { gql, GraphQLClient } from '../src/entrypoints/main.js' import { expect, test, vitest } from 'vitest' +import { gql, GraphQLClient } from '../src/entrypoints/main.js' test(`custom fetch configuration is passed through`, async () => { const fetch = vitest.fn().mockResolvedValue({ ok: true, headers: new Headers(), text: () => ``, data: {} }) diff --git a/tests/general.test.ts b/tests/general.test.ts index 1f12d9b5b..8e84b3a1b 100644 --- a/tests/general.test.ts +++ b/tests/general.test.ts @@ -1,8 +1,8 @@ -import { GraphQLClient, rawRequest, request } from '../src/entrypoints/main.js' -import { errors, setupMockServer } from './__helpers.js' import { gql } from 'graphql-tag' import type { Mock } from 'vitest' import { beforeEach, describe, expect, it, test, vitest } from 'vitest' +import { GraphQLClient, rawRequest, request } from '../src/entrypoints/main.js' +import { errors, setupMockServer } from './__helpers.js' const ctx = setupMockServer() diff --git a/tests/gql.test.ts b/tests/gql.test.ts index a40f220c4..a05321dc4 100644 --- a/tests/gql.test.ts +++ b/tests/gql.test.ts @@ -1,7 +1,7 @@ -import { request } from '../src/entrypoints/main.js' -import { setupMockServer } from './__helpers.js' import { gql } from 'graphql-tag' import { describe, expect, it } from 'vitest' +import { request } from '../src/entrypoints/main.js' +import { setupMockServer } from './__helpers.js' const ctx = setupMockServer() diff --git a/tests/headers.test.ts b/tests/headers.test.ts index 14371c1a8..d09b708ce 100644 --- a/tests/headers.test.ts +++ b/tests/headers.test.ts @@ -1,6 +1,6 @@ +import { describe, expect, test } from 'vitest' import { GraphQLClient, request } from '../src/entrypoints/main.js' import { setupMockServer } from './__helpers.js' -import { describe, expect, test } from 'vitest' const ctx = setupMockServer() diff --git a/tests/httpMethod.test.ts b/tests/httpMethod.test.ts index da0af7366..a81691b5a 100644 --- a/tests/httpMethod.test.ts +++ b/tests/httpMethod.test.ts @@ -1,7 +1,7 @@ +import { expect, test, vitest } from 'vitest' import { gql, GraphQLClient } from '../src/entrypoints/main.js' import type { RequestConfig } from '../src/legacy/helpers/types.js' import { CONTENT_TYPE_HEADER, statusCodes } from '../src/lib/http.js' -import { expect, test, vitest } from 'vitest' test(`mutation forces a POST method even if input wants GET for query`, async () => { const fetch = vitest.fn().mockImplementation((_: string, requestConfig: RequestConfig) => { diff --git a/tests/json-serializer.test.ts b/tests/json-serializer.test.ts index 4b18d1876..a38365e7c 100644 --- a/tests/json-serializer.test.ts +++ b/tests/json-serializer.test.ts @@ -1,8 +1,8 @@ +import { beforeEach, describe, expect, test, vitest } from 'vitest' import { GraphQLClient } from '../src/entrypoints/main.js' import type { Fetch, Variables } from '../src/legacy/helpers/types.js' import { CONTENT_TYPE_HEADER, statusCodes } from '../src/lib/http.js' import { setupMockServer } from './__helpers.js' -import { beforeEach, describe, expect, test, vitest } from 'vitest' const ctx = setupMockServer() @@ -36,19 +36,15 @@ describe(`is used for serializing variables`, () => { const simpleVariable = { name: `test` } let client: GraphQLClient - const testSingleQuery = - (expectedNumStringifyCalls?: number, variables: Variables = simpleVariable) => - async () => { - await client.request(document, variables) - expect(client.requestConfig.jsonSerializer?.stringify).toBeCalledTimes(expectedNumStringifyCalls ?? 1) - } + const testSingleQuery = (expectedNumStringifyCalls?: number, variables: Variables = simpleVariable) => async () => { + await client.request(document, variables) + expect(client.requestConfig.jsonSerializer?.stringify).toBeCalledTimes(expectedNumStringifyCalls ?? 1) + } - const testBatchQuery = - (expectedNumStringifyCalls?: number, variables: Variables = simpleVariable) => - async () => { - await client.batchRequests([{ document, variables }]) - expect(client.requestConfig.jsonSerializer?.stringify).toBeCalledTimes(expectedNumStringifyCalls ?? 1) - } + const testBatchQuery = (expectedNumStringifyCalls?: number, variables: Variables = simpleVariable) => async () => { + await client.batchRequests([{ document, variables }]) + expect(client.requestConfig.jsonSerializer?.stringify).toBeCalledTimes(expectedNumStringifyCalls ?? 1) + } describe(`request body`, () => { beforeEach(() => { diff --git a/tests/signal.test.ts b/tests/signal.test.ts index c1673e5b3..7e73cd509 100644 --- a/tests/signal.test.ts +++ b/tests/signal.test.ts @@ -1,6 +1,6 @@ +import { expect, it } from 'vitest' import { batchRequests, GraphQLClient, rawRequest, request } from '../src/entrypoints/main.js' import { setupMockServer, sleep } from './__helpers.js' -import { expect, it } from 'vitest' const ctx = setupMockServer(20) diff --git a/tests/typed-document-node.test.ts b/tests/typed-document-node.test.ts index 9b09d69cc..17a9164ac 100644 --- a/tests/typed-document-node.test.ts +++ b/tests/typed-document-node.test.ts @@ -1,8 +1,8 @@ -import request, { gql } from '../src/entrypoints/main.js' -import { setupMockServer } from './__helpers.js' import type { TypedDocumentNode } from '@graphql-typed-document-node/core' import { parse } from 'graphql' import { expect, test } from 'vitest' +import request, { gql } from '../src/entrypoints/main.js' +import { setupMockServer } from './__helpers.js' const ctx = setupMockServer() diff --git a/tsconfig.json b/tsconfig.json index f4887aca8..673dc5feb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -23,8 +23,8 @@ // Other "skipLibCheck": true, - "esModuleInterop": true, + "esModuleInterop": true }, "include": ["src", "tests", "examples"], - "exclude": ["build"], + "exclude": ["build"] }