@shopify/graphql-client
Advanced tools
Comparing version 0.3.0 to 0.4.0
@@ -1,3 +0,3 @@ | ||
export { createGraphQLClient } from "./graphql-client"; | ||
export type * from "./types"; | ||
export * from "./graphql-client"; | ||
export * from "./api-client-utilities"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,2 +0,3 @@ | ||
export { createGraphQLClient } from "./graphql-client"; | ||
export * from "./graphql-client"; | ||
export * from "./api-client-utilities"; | ||
//# sourceMappingURL=index.js.map |
@@ -25,5 +25,4 @@ type CustomFetchAPI = (url: string, init?: { | ||
} | ||
type LogType = "HTTP-Response" | "HTTP-Retry"; | ||
interface LogContent { | ||
type: LogType; | ||
type: string; | ||
content: any; | ||
@@ -48,2 +47,3 @@ } | ||
type LogContentTypes = HTTPResponseLog | HTTPRetryLog; | ||
type Logger<TLogContentTypes = LogContentTypes> = (logContent: TLogContentTypes) => void; | ||
interface ClientOptions { | ||
@@ -54,3 +54,3 @@ headers: Headers; | ||
retries?: number; | ||
logger?: (logContent: LogContentTypes) => void; | ||
logger?: Logger; | ||
} | ||
@@ -60,3 +60,3 @@ interface ClientConfig { | ||
readonly url: ClientOptions["url"]; | ||
readonly retries: ClientOptions["retries"]; | ||
readonly retries: Required<ClientOptions>["retries"]; | ||
} | ||
@@ -78,2 +78,56 @@ interface RequestOptions { | ||
export { ClientConfig, ClientOptions, ClientResponse, CustomFetchAPI, GQLExtensions, GraphQLClient, HTTPResponseLog, HTTPRetryLog, Headers, LogContent, LogContentTypes, LogType, OperationVariables, RequestOptions, RequestParams, ResponseError, createGraphQLClient }; | ||
interface UnsupportedApiVersionLog extends LogContent { | ||
type: "UNSUPPORTED_API_VERSION"; | ||
content: { | ||
apiVersion: string; | ||
supportedApiVersions: string[]; | ||
}; | ||
} | ||
type APIClientLogContentTypes = LogContentTypes | UnsupportedApiVersionLog; | ||
type APIClientLogger<TLogContentTypes = APIClientLogContentTypes> = Logger<TLogContentTypes>; | ||
interface APIClientConfig { | ||
readonly storeDomain: string; | ||
readonly apiVersion: string; | ||
readonly headers: Headers; | ||
readonly apiUrl: string; | ||
readonly retries?: number; | ||
} | ||
interface APIClientRequestOptions { | ||
variables?: OperationVariables; | ||
apiVersion?: string; | ||
customHeaders?: Headers; | ||
retries?: number; | ||
} | ||
type APIClientRequestParams = [ | ||
operation: string, | ||
options?: APIClientRequestOptions | ||
]; | ||
interface APIClient<TClientConfig extends APIClientConfig> { | ||
readonly config: TClientConfig; | ||
getHeaders: (customHeaders?: Headers) => Headers; | ||
getApiUrl: (apiVersion?: string) => string; | ||
fetch: (...props: APIClientRequestParams) => ReturnType<GraphQLClient["fetch"]>; | ||
request: <TData = unknown>(...props: APIClientRequestParams) => Promise<ClientResponse<TData>>; | ||
} | ||
declare function getErrorMessage(error: any): string; | ||
declare function validateRetries(retries?: number): void; | ||
declare function validateRequiredStoreDomain(errorPrefix: string, storeDomain: string | undefined): void; | ||
declare function validateApiVersion({ errorPrefix, currentSupportedApiVersions, apiVersion, logger, }: { | ||
errorPrefix: string; | ||
currentSupportedApiVersions: string[]; | ||
apiVersion: string; | ||
logger?: APIClientLogger; | ||
}): void; | ||
declare function getCurrentAPIVersion(): { | ||
year: number; | ||
quarter: number; | ||
version: string; | ||
}; | ||
declare function getCurrentSupportedAPIVersions(): string[]; | ||
declare function getDomain(url: string): string; | ||
export { APIClient, APIClientConfig, APIClientLogContentTypes, APIClientLogger, APIClientRequestOptions, APIClientRequestParams, ClientConfig, ClientOptions, ClientResponse, CustomFetchAPI, GQLExtensions, GraphQLClient, HTTPResponseLog, HTTPRetryLog, Headers, LogContent, LogContentTypes, Logger, OperationVariables, RequestOptions, RequestParams, ResponseError, UnsupportedApiVersionLog, createGraphQLClient, getCurrentAPIVersion, getCurrentSupportedAPIVersions, getDomain, getErrorMessage, validateApiVersion, validateRequiredStoreDomain, validateRetries }; |
'use strict'; | ||
var graphqlClient = require('./graphql-client.js'); | ||
var graphqlClient = require('./graphql-client/graphql-client.js'); | ||
var validations = require('./api-client-utilities/validations.js'); | ||
var apiVersions = require('./api-client-utilities/api-versions.js'); | ||
var utilities$1 = require('./api-client-utilities/utilities.js'); | ||
var utilities = require('./graphql-client/utilities.js'); | ||
@@ -8,2 +12,9 @@ | ||
exports.createGraphQLClient = graphqlClient.createGraphQLClient; | ||
exports.validateApiVersion = validations.validateApiVersion; | ||
exports.validateRequiredStoreDomain = validations.validateRequiredStoreDomain; | ||
exports.getCurrentAPIVersion = apiVersions.getCurrentAPIVersion; | ||
exports.getCurrentSupportedAPIVersions = apiVersions.getCurrentSupportedAPIVersions; | ||
exports.getDomain = utilities$1.getDomain; | ||
exports.getErrorMessage = utilities.getErrorMessage; | ||
exports.validateRetries = utilities.validateRetries; | ||
//# sourceMappingURL=index.js.map |
@@ -1,3 +0,3 @@ | ||
export { createGraphQLClient } from "./graphql-client"; | ||
export type * from "./types"; | ||
export * from "./graphql-client"; | ||
export * from "./api-client-utilities"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -8,7 +8,16 @@ /*! shopify/graphql-client -- Copyright (c) 2023-present, Shopify Inc. -- license (MIT): https://github.com///github/blob/main/LICENSE */ | ||
const ERROR_PREFIX = "GraphQL Client:"; | ||
const MIN_RETRIES = 0; | ||
const MAX_RETRIES = 3; | ||
function getErrorMessage(error) { | ||
return error instanceof Error ? error.message : JSON.stringify(error); | ||
} | ||
function validateRetries(retries) { | ||
if (retries !== undefined && | ||
(retries < MIN_RETRIES || retries > MAX_RETRIES)) { | ||
throw new Error(`${ERROR_PREFIX} The provided "retries" value (${retries}) is invalid - it cannot be less than ${MIN_RETRIES} or greater than ${MAX_RETRIES}`); | ||
} | ||
} | ||
const ERROR_PREFIX = "GraphQL Client:"; | ||
const GQL_API_ERROR = `${ERROR_PREFIX} An error occurred while fetching from the API. Review 'graphQLErrors' for details.`; | ||
@@ -20,6 +29,21 @@ const UNEXPECTED_CONTENT_TYPE_ERROR = `${ERROR_PREFIX} Response returned unexpected Content-Type:`; | ||
}; | ||
const MIN_RETRIES = 0; | ||
const MAX_RETRIES = 3; | ||
const RETRY_WAIT_TIME = 1000; | ||
const RETRIABLE_STATUS_CODES = [429, 503]; | ||
function createGraphQLClient({ headers, url, fetchAPI = fetch, retries = 0, logger, }) { | ||
validateRetries(retries); | ||
const config = { | ||
headers, | ||
url, | ||
retries, | ||
}; | ||
const clientLogger = generateClientLogger(logger); | ||
const httpFetch = generateHttpFetch(fetchAPI, clientLogger); | ||
const fetch = generateFetch(httpFetch, config); | ||
const request = generateRequest(fetch); | ||
return { | ||
config, | ||
fetch, | ||
request, | ||
}; | ||
} | ||
async function sleep(waitTime) { | ||
@@ -48,16 +72,4 @@ return new Promise((resolve) => setTimeout(resolve, waitTime)); | ||
} | ||
function validateRetries(retries) { | ||
if (retries !== undefined && | ||
(retries < MIN_RETRIES || retries > MAX_RETRIES)) { | ||
throw new Error(`${ERROR_PREFIX} The provided "retries" value (${retries}) is invalid - it cannot be less than ${MIN_RETRIES} or greater than ${MAX_RETRIES}`); | ||
} | ||
} | ||
function createGraphQLClient({ headers, url, fetchAPI = fetch, retries = 0, logger, }) { | ||
validateRetries(retries); | ||
const config = { | ||
headers, | ||
url, | ||
retries, | ||
}; | ||
const clientLogger = (logContent) => { | ||
function generateClientLogger(logger) { | ||
return (logContent) => { | ||
if (logger) { | ||
@@ -67,2 +79,4 @@ logger(logContent); | ||
}; | ||
} | ||
function generateHttpFetch(fetchAPI, clientLogger) { | ||
const httpFetch = async (requestParams, count, maxRetries) => { | ||
@@ -107,3 +121,6 @@ const nextCount = count + 1; | ||
}; | ||
const fetch = async (operation, options = {}) => { | ||
return httpFetch; | ||
} | ||
function generateFetch(httpFetch, { url, headers, retries }) { | ||
return async (operation, options = {}) => { | ||
const { variables, headers: overrideHeaders, url: overrideUrl, retries: overrideRetries, } = options; | ||
@@ -128,3 +145,5 @@ const body = JSON.stringify({ | ||
}; | ||
const request = async (...props) => { | ||
} | ||
function generateRequest(fetch) { | ||
return async (...props) => { | ||
try { | ||
@@ -160,7 +179,2 @@ const response = await fetch(...props); | ||
}; | ||
return { | ||
config, | ||
fetch, | ||
request, | ||
}; | ||
} | ||
@@ -167,0 +181,0 @@ |
/*! shopify/graphql-client -- Copyright (c) 2023-present, Shopify Inc. -- license (MIT): https://github.com///github/blob/main/LICENSE */ | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).ShopifyGraphQLClient={})}(this,(function(e){"use strict";function r(e){return e instanceof Error?e.message:JSON.stringify(e)}const t="GraphQL Client:",n=`${t} An error occurred while fetching from the API. Review 'graphQLErrors' for details.`,s=`${t} Response returned unexpected Content-Type:`,o="application/json",a=0,i=3,u=[429,503];function c(e){if(void 0!==e&&(e<a||e>i))throw new Error(`${t} The provided "retries" value (${e}) is invalid - it cannot be less than ${a} or greater than ${i}`)}e.createGraphQLClient=function({headers:e,url:a,fetchAPI:i=fetch,retries:d=0,logger:f}){c(d);const h=e=>{f&&f(e)},p=async(e,n,s)=>{const o=n+1,a=s+1;let c;try{if(c=await i(...e),h({type:"HTTP-Response",content:{requestParams:e,response:c}}),!c.ok&&u.includes(c.status)&&o<=a)throw new Error;return c}catch(i){if(o<=a)return await async function(e){return new Promise((r=>setTimeout(r,e)))}(1e3),h({type:"HTTP-Retry",content:{requestParams:e,lastResponse:c,retryAttempt:n,maxRetries:s}}),p(e,o,s);throw new Error(`${t}${s>0?` Attempted maximum number of ${s} network retries. Last message -`:""} ${r(i)}`)}},fetch=async(r,t={})=>{const{variables:n,headers:s,url:o,retries:i}=t,u=JSON.stringify({query:r,variables:n});c(i);const f=[o??a,{method:"POST",headers:{...e,...s},body:u}];return p(f,1,i??d)};return{config:{headers:e,url:a,retries:d},fetch:fetch,request:async(...e)=>{try{const r=await fetch(...e),{status:a,statusText:i}=r,u=r.headers.get("content-type")||"";return r.ok?u.includes(o)?async function(e){const{errors:r,data:s,extensions:o}=await e.json(),a=o?{extensions:o}:{};return r||!s?{error:{networkStatusCode:e.status,message:r?n:`${t} An unknown error has occurred. The API did not return a data object or any errors in its response.`,...r?{graphQLErrors:r}:{}},...a}:{data:s,...a}}(r):{error:{networkStatusCode:a,message:`${s} ${u}`}}:{error:{networkStatusCode:a,message:i}}}catch(e){return{error:{message:r(e)}}}}}}})); | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).ShopifyGraphQLClient={})}(this,(function(e){"use strict";const r="GraphQL Client:",t=0,n=3;function s(e){return e instanceof Error?e.message:JSON.stringify(e)}function o(e){if(void 0!==e&&(e<t||e>n))throw new Error(`${r} The provided "retries" value (${e}) is invalid - it cannot be less than ${t} or greater than ${n}`)}const a=`${r} An error occurred while fetching from the API. Review 'graphQLErrors' for details.`,i=`${r} Response returned unexpected Content-Type:`,u={json:"application/json",multipart:"multipart/mixed"},c=1e3,d=[429,503];e.createGraphQLClient=function({headers:e,url:t,fetchAPI:n=m,retries:f=0,logger:h}){o(f);const p={headers:e,url:t,retries:f},l=function(e){return r=>{e&&e(r)}}(h),m=function(e,{url:r,headers:t,retries:n}){return async(s,a={})=>{const{variables:i,headers:u,url:c,retries:d}=a,f=JSON.stringify({query:s,variables:i});o(d);const h=[c??r,{method:"POST",headers:{...t,...u},body:f}];return e(h,1,d??n)}}(function(e,t){const n=async(o,a,i)=>{const u=a+1,f=i+1;let h;try{if(h=await e(...o),t({type:"HTTP-Response",content:{requestParams:o,response:h}}),!h.ok&&d.includes(h.status)&&u<=f)throw new Error;return h}catch(e){if(u<=f)return await async function(e){return new Promise((r=>setTimeout(r,e)))}(c),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:a,maxRetries:i}}),n(o,u,i);throw new Error(`${r}${i>0?` Attempted maximum number of ${i} network retries. Last message -`:""} ${s(e)}`)}};return n}(n,l),p),y=function(e){return async(...t)=>{try{const n=await e(...t),{status:s,statusText:o}=n,c=n.headers.get("content-type")||"";return n.ok?c.includes(u.json)?async function(e){const{errors:t,data:n,extensions:s}=await e.json(),o=s?{extensions:s}:{};if(t||!n)return{error:{networkStatusCode:e.status,message:t?a:`${r} An unknown error has occurred. The API did not return a data object or any errors in its response.`,...t?{graphQLErrors:t}:{}},...o};return{data:n,...o}}(n):{error:{networkStatusCode:s,message:`${i} ${c}`}}:{error:{networkStatusCode:s,message:o}}}catch(e){return{error:{message:s(e)}}}}}(m);return{config:p,fetch:m,request:y}}})); | ||
//# sourceMappingURL=graphql-client.min.js.map |
{ | ||
"name": "@shopify/graphql-client", | ||
"version": "0.3.0", | ||
"version": "0.4.0", | ||
"description": "Shopify GraphQL Client - A lightweight generic GraphQL JS client to interact with Shopify GraphQL APIs", | ||
@@ -5,0 +5,0 @@ "repository": { |
@@ -5,5 +5,14 @@ # GraphQL Client | ||
## Initialization | ||
## Getting Started | ||
To install this package, you can run this in your terminal: | ||
```typescript | ||
npm install @shopify/graphql-client | ||
``` | ||
## Client initialization | ||
```typescript | ||
import {createGraphQLClient} from '@shopify/graphql-client'; | ||
@@ -10,0 +19,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
113380
102
1353
221
17