@shopify/admin-api-client
Advanced tools
Comparing version 0.1.0 to 0.2.0
@@ -1,2 +0,3 @@ | ||
import { CustomFetchApi, ApiClientLogger, ApiClient, ApiClientLogContentTypes, ApiClientConfig } from '@shopify/graphql-client'; | ||
import { ApiClientConfig, CustomFetchApi, ApiClientLogger, ApiClientLogContentTypes, ApiClient } from '@shopify/graphql-client'; | ||
export { AllOperations, ApiClientRequestOptions, ClientResponse, FetchResponseBody, HTTPResponseLog, HTTPRetryLog, LogContent, ResponseWithType, ReturnData } from '@shopify/graphql-client'; | ||
@@ -12,2 +13,3 @@ type AdminApiClientLogContentTypes = ApiClientLogContentTypes; | ||
}; | ||
interface AdminQueries { | ||
@@ -18,2 +20,3 @@ [key: string]: { | ||
}; | ||
[key: number | symbol]: never; | ||
} | ||
@@ -25,2 +28,3 @@ interface AdminMutations { | ||
}; | ||
[key: number | symbol]: never; | ||
} | ||
@@ -32,2 +36,34 @@ type AdminOperations = AdminQueries & AdminMutations; | ||
export { AdminMutations, AdminQueries, createAdminApiClient }; | ||
type SearchParamField = string | number; | ||
type SearchParamFields = SearchParamField | SearchParamField[] | Record<string, SearchParamField | SearchParamField[]>; | ||
type SearchParams = Record<string, SearchParamFields>; | ||
type HeaderOptions = Record<string, string | number | string[]>; | ||
interface GetRequestOptions { | ||
headers?: HeaderOptions; | ||
data?: Record<string, any> | string; | ||
searchParams?: SearchParams; | ||
retries?: number; | ||
apiVersion?: string; | ||
} | ||
interface PostRequestOptions extends GetRequestOptions { | ||
data: Required<GetRequestOptions>["data"]; | ||
} | ||
interface PutRequestOptions extends PostRequestOptions { | ||
} | ||
interface DeleteRequestOptions extends GetRequestOptions { | ||
} | ||
interface AdminRestApiClientOptions extends AdminApiClientOptions { | ||
scheme?: "https" | "http"; | ||
defaultRetryTime?: number; | ||
formatPaths?: boolean; | ||
} | ||
interface AdminRestApiClient { | ||
get: (path: string, options?: GetRequestOptions) => ReturnType<CustomFetchApi>; | ||
put: (path: string, options?: PutRequestOptions) => ReturnType<CustomFetchApi>; | ||
post: (path: string, options?: PostRequestOptions) => ReturnType<CustomFetchApi>; | ||
delete: (path: string, options?: DeleteRequestOptions) => ReturnType<CustomFetchApi>; | ||
} | ||
declare function createAdminRestApiClient({ storeDomain, apiVersion, accessToken, userAgentPrefix, logger, customFetchApi, retries: clientRetries, scheme, defaultRetryTime, formatPaths, }: AdminRestApiClientOptions): AdminRestApiClient; | ||
export { AdminApiClient, AdminMutations, AdminOperations, AdminQueries, AdminRestApiClient, SearchParams, createAdminApiClient, createAdminRestApiClient }; |
@@ -5,5 +5,7 @@ 'use strict'; | ||
// This is value is replaced with package.json version during rollup build process | ||
const DEFAULT_CLIENT_VERSION = "0.1.0"; | ||
const DEFAULT_CLIENT_VERSION = "0.2.0"; | ||
const ACCESS_TOKEN_HEADER = "X-Shopify-Access-Token"; | ||
const CLIENT = "Admin API Client"; | ||
const RETRIABLE_STATUS_CODES = [429, 500, 503]; | ||
const DEFAULT_RETRY_WAIT_TIME = 1000; | ||
@@ -14,2 +16,4 @@ exports.ACCESS_TOKEN_HEADER = ACCESS_TOKEN_HEADER; | ||
exports.DEFAULT_CONTENT_TYPE = DEFAULT_CONTENT_TYPE; | ||
exports.DEFAULT_RETRY_WAIT_TIME = DEFAULT_RETRY_WAIT_TIME; | ||
exports.RETRIABLE_STATUS_CODES = RETRIABLE_STATUS_CODES; | ||
//# sourceMappingURL=constants.js.map |
@@ -8,3 +8,3 @@ 'use strict'; | ||
} | ||
function generateGetGQLClientParams({ getHeaders, getApiUrl, }) { | ||
function generateGetGQLClientParams({ getHeaders, getApiUrl }) { | ||
return (operation, options) => { | ||
@@ -11,0 +11,0 @@ const props = [operation]; |
@@ -22,3 +22,3 @@ 'use strict'; | ||
const versionError = `${client}: the provided apiVersion ("${apiVersion}")`; | ||
const supportedVersion = `Current supported API versions: ${currentSupportedApiVersions.join(", ")}`; | ||
const supportedVersion = `Currently supported API versions: ${currentSupportedApiVersions.join(", ")}`; | ||
if (!apiVersion || typeof apiVersion !== "string") { | ||
@@ -31,3 +31,3 @@ throw new Error(`${versionError} is invalid. ${supportedVersion}`); | ||
logger({ | ||
type: "UNSUPPORTED_API_VERSION", | ||
type: "Unsupported_Api_Version", | ||
content: { | ||
@@ -40,3 +40,3 @@ apiVersion, | ||
else { | ||
console.warn(`${versionError} is deprecated or not supported. ${supportedVersion}`); | ||
console.warn(`${versionError} is likely deprecated or not supported. ${supportedVersion}`); | ||
} | ||
@@ -43,0 +43,0 @@ } |
@@ -6,6 +6,21 @@ 'use strict'; | ||
const MAX_RETRIES = 3; | ||
const GQL_API_ERROR = "An error occurred while fetching from the API. Review 'graphQLErrors' for details."; | ||
const UNEXPECTED_CONTENT_TYPE_ERROR = "Response returned unexpected Content-Type:"; | ||
const NO_DATA_OR_ERRORS_ERROR = "An unknown error has occurred. The API did not return a data object or any errors in its response."; | ||
const CONTENT_TYPES = { | ||
json: "application/json", | ||
multipart: "multipart/mixed", | ||
}; | ||
const RETRY_WAIT_TIME = 1000; | ||
const RETRIABLE_STATUS_CODES = [429, 503]; | ||
exports.CLIENT = CLIENT; | ||
exports.CONTENT_TYPES = CONTENT_TYPES; | ||
exports.GQL_API_ERROR = GQL_API_ERROR; | ||
exports.MAX_RETRIES = MAX_RETRIES; | ||
exports.MIN_RETRIES = MIN_RETRIES; | ||
exports.NO_DATA_OR_ERRORS_ERROR = NO_DATA_OR_ERRORS_ERROR; | ||
exports.RETRIABLE_STATUS_CODES = RETRIABLE_STATUS_CODES; | ||
exports.RETRY_WAIT_TIME = RETRY_WAIT_TIME; | ||
exports.UNEXPECTED_CONTENT_TYPE_ERROR = UNEXPECTED_CONTENT_TYPE_ERROR; | ||
//# sourceMappingURL=constants.js.map |
'use strict'; | ||
var httpFetch = require('./http-fetch.js'); | ||
var constants = require('./constants.js'); | ||
var utilities = require('./utilities.js'); | ||
const GQL_API_ERROR = `${constants.CLIENT}: An error occurred while fetching from the API. Review 'graphQLErrors' for details.`; | ||
const UNEXPECTED_CONTENT_TYPE_ERROR = `${constants.CLIENT}: Response returned unexpected Content-Type:`; | ||
const CONTENT_TYPES = { | ||
json: "application/json", | ||
multipart: "multipart/mixed", | ||
}; | ||
const RETRY_WAIT_TIME = 1000; | ||
const RETRIABLE_STATUS_CODES = [429, 503]; | ||
function createGraphQLClient({ headers, url, fetchApi = fetch, retries = 0, logger, }) { | ||
@@ -22,4 +15,8 @@ utilities.validateRetries({ client: constants.CLIENT, retries }); | ||
const clientLogger = generateClientLogger(logger); | ||
const httpFetch = generateHttpFetch(fetchApi, clientLogger); | ||
const fetch = generateFetch(httpFetch, config); | ||
const httpFetch$1 = httpFetch.generateHttpFetch({ | ||
fetchApi, | ||
clientLogger, | ||
defaultRetryWaitTime: constants.RETRY_WAIT_TIME, | ||
}); | ||
const fetch = generateFetch(httpFetch$1, config); | ||
const request = generateRequest(fetch); | ||
@@ -32,4 +29,8 @@ return { | ||
} | ||
async function sleep(waitTime) { | ||
return new Promise((resolve) => setTimeout(resolve, waitTime)); | ||
function generateClientLogger(logger) { | ||
return (logContent) => { | ||
if (logger) { | ||
logger(logContent); | ||
} | ||
}; | ||
} | ||
@@ -39,4 +40,4 @@ async function processJSONResponse(response) { | ||
return { | ||
...(data ? { data } : {}), | ||
...(extensions ? { extensions } : {}), | ||
...utilities.getKeyValueIfValid("data", data), | ||
...utilities.getKeyValueIfValid("extensions", extensions), | ||
...(errors || !data | ||
@@ -46,6 +47,5 @@ ? { | ||
networkStatusCode: response.status, | ||
message: errors | ||
? GQL_API_ERROR | ||
: `${constants.CLIENT}: An unknown error has occurred. The API did not return a data object or any errors in its response.`, | ||
...(errors ? { graphQLErrors: errors } : {}), | ||
message: utilities.formatErrorMessage(errors ? constants.GQL_API_ERROR : constants.NO_DATA_OR_ERRORS_ERROR), | ||
...utilities.getKeyValueIfValid("graphQLErrors", errors), | ||
response, | ||
}, | ||
@@ -56,51 +56,2 @@ } | ||
} | ||
function generateClientLogger(logger) { | ||
return (logContent) => { | ||
if (logger) { | ||
logger(logContent); | ||
} | ||
}; | ||
} | ||
function generateHttpFetch(fetchApi, clientLogger) { | ||
const httpFetch = async (requestParams, count, maxRetries) => { | ||
const nextCount = count + 1; | ||
const maxTries = maxRetries + 1; | ||
let response; | ||
try { | ||
response = await fetchApi(...requestParams); | ||
clientLogger({ | ||
type: "HTTP-Response", | ||
content: { | ||
requestParams, | ||
response, | ||
}, | ||
}); | ||
if (!response.ok && | ||
RETRIABLE_STATUS_CODES.includes(response.status) && | ||
nextCount <= maxTries) { | ||
throw new Error(); | ||
} | ||
return response; | ||
} | ||
catch (error) { | ||
if (nextCount <= maxTries) { | ||
await sleep(RETRY_WAIT_TIME); | ||
clientLogger({ | ||
type: "HTTP-Retry", | ||
content: { | ||
requestParams, | ||
lastResponse: response, | ||
retryAttempt: count, | ||
maxRetries, | ||
}, | ||
}); | ||
return httpFetch(requestParams, nextCount, maxRetries); | ||
} | ||
throw new Error(`${constants.CLIENT}:${maxRetries > 0 | ||
? ` Attempted maximum number of ${maxRetries} network retries. Last message -` | ||
: ""} ${utilities.getErrorMessage(error)}`); | ||
} | ||
}; | ||
return httpFetch; | ||
} | ||
function generateFetch(httpFetch, { url, headers, retries }) { | ||
@@ -114,2 +65,6 @@ return async (operation, options = {}) => { | ||
utilities.validateRetries({ client: constants.CLIENT, retries: overrideRetries }); | ||
const flatHeaders = Object.fromEntries(Object.entries({ ...headers, ...overrideHeaders }).map(([key, value]) => [ | ||
key, | ||
Array.isArray(value) ? value.join(", ") : value.toString(), | ||
])); | ||
const fetchParams = [ | ||
@@ -119,6 +74,3 @@ overrideUrl ?? url, | ||
method: "POST", | ||
headers: { | ||
...headers, | ||
...overrideHeaders, | ||
}, | ||
headers: flatHeaders, | ||
body, | ||
@@ -140,11 +92,13 @@ }, | ||
networkStatusCode: status, | ||
message: statusText, | ||
message: utilities.formatErrorMessage(statusText), | ||
response, | ||
}, | ||
}; | ||
} | ||
if (!contentType.includes(CONTENT_TYPES.json)) { | ||
if (!contentType.includes(constants.CONTENT_TYPES.json)) { | ||
return { | ||
errors: { | ||
networkStatusCode: status, | ||
message: `${UNEXPECTED_CONTENT_TYPE_ERROR} ${contentType}`, | ||
message: utilities.formatErrorMessage(`${constants.UNEXPECTED_CONTENT_TYPE_ERROR} ${contentType}`), | ||
response, | ||
}, | ||
@@ -151,0 +105,0 @@ }; |
@@ -5,2 +5,5 @@ 'use strict'; | ||
function formatErrorMessage(message, client = constants.CLIENT) { | ||
return message.startsWith(`${client}`) ? message : `${client}: ${message}`; | ||
} | ||
function getErrorMessage(error) { | ||
@@ -17,5 +20,15 @@ return error instanceof Error ? error.message : JSON.stringify(error); | ||
} | ||
function getKeyValueIfValid(key, value) { | ||
return value && | ||
(typeof value !== "object" || | ||
Array.isArray(value) || | ||
(typeof value === "object" && Object.keys(value).length > 0)) | ||
? { [key]: value } | ||
: {}; | ||
} | ||
exports.formatErrorMessage = formatErrorMessage; | ||
exports.getErrorMessage = getErrorMessage; | ||
exports.getKeyValueIfValid = getKeyValueIfValid; | ||
exports.validateRetries = validateRetries; | ||
//# sourceMappingURL=utilities.js.map |
'use strict'; | ||
var adminApiClient = require('./admin-api-client.js'); | ||
var client = require('./graphql/client.js'); | ||
var client$1 = require('./rest/client.js'); | ||
exports.createAdminApiClient = adminApiClient.createAdminApiClient; | ||
exports.createAdminApiClient = client.createAdminApiClient; | ||
exports.createAdminRestApiClient = client$1.createAdminRestApiClient; | ||
//# sourceMappingURL=index.js.map |
@@ -5,2 +5,4 @@ export declare const DEFAULT_CONTENT_TYPE = "application/json"; | ||
export declare const CLIENT = "Admin API Client"; | ||
export declare const RETRIABLE_STATUS_CODES: number[]; | ||
export declare const DEFAULT_RETRY_WAIT_TIME = 1000; | ||
//# sourceMappingURL=constants.d.ts.map |
@@ -1,3 +0,6 @@ | ||
export { createAdminApiClient } from "./admin-api-client"; | ||
export { AdminQueries, AdminMutations } from "./types"; | ||
export { createAdminApiClient } from "./graphql"; | ||
export { AdminApiClient, AdminQueries, AdminMutations, AdminOperations, } from "./graphql/types"; | ||
export { createAdminRestApiClient } from "./rest"; | ||
export { AdminRestApiClient, SearchParams } from "./rest/types"; | ||
export type { AllOperations, ApiClientRequestOptions, ClientResponse, FetchResponseBody, HTTPResponseLog, HTTPRetryLog, LogContent, ResponseWithType, ReturnData, } from "@shopify/graphql-client"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,2 +0,2 @@ | ||
import { ApiClient, CustomFetchApi, ApiClientLogger, ApiClientLogContentTypes, ApiClientConfig } from "@shopify/graphql-client"; | ||
import { CustomFetchApi, ApiClientLogger, ApiClientLogContentTypes, ApiClientConfig } from "@shopify/graphql-client"; | ||
export type AdminApiClientLogContentTypes = ApiClientLogContentTypes; | ||
@@ -11,16 +11,2 @@ export type AdminApiClientConfig = ApiClientConfig & { | ||
}; | ||
export interface AdminQueries { | ||
[key: string]: { | ||
variables: any; | ||
return: any; | ||
}; | ||
} | ||
export interface AdminMutations { | ||
[key: string]: { | ||
variables: any; | ||
return: any; | ||
}; | ||
} | ||
export type AdminOperations = AdminQueries & AdminMutations; | ||
export type AdminApiClient = ApiClient<AdminApiClientConfig, AdminOperations>; | ||
//# sourceMappingURL=types.d.ts.map |
{ | ||
"name": "@shopify/admin-api-client", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"description": "Shopify Admin API Client - A lightweight JS client to interact with Shopify's Admin API", | ||
@@ -11,5 +11,5 @@ "repository": { | ||
"license": "MIT", | ||
"main": "./dist/admin-api-client.min.js", | ||
"main": "./dist/index.js", | ||
"module": "./dist/index.mjs", | ||
"types": "./dist/admin-api-client.d.ts", | ||
"types": "./dist/ts/index.d.ts", | ||
"exports": { | ||
@@ -64,7 +64,7 @@ ".": { | ||
"dependencies": { | ||
"@shopify/graphql-client": "^0.8.0" | ||
"@shopify/graphql-client": "^0.9.0" | ||
}, | ||
"devDependencies": { | ||
"jest-environment-jsdom": "^29.5.0", | ||
"regenerator-runtime": "^0.14.0" | ||
"regenerator-runtime": "^0.14.1" | ||
}, | ||
@@ -71,0 +71,0 @@ "bugs": { |
170
README.md
@@ -45,2 +45,5 @@ # Admin API Client | ||
> [!NOTE] | ||
> If you want to query the Admin REST API, you can [use the REST client](#using-the-rest-api-client) instead. | ||
### `createAdminApiClient()` parameters | ||
@@ -55,4 +58,4 @@ | ||
| retries? | `number` | The number of HTTP request retries if the request was abandoned or the server responded with a `Too Many Requests (429)` or `Service Unavailable (503)` response. Default value is `0`. Maximum value is `3`. | | ||
| customFetchAPI? | `(url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response>` | A replacement `fetch` function that will be used in all client network requests. By default, the client uses `window.fetch()`. | | ||
| logger? | `(logContent:`[UnsupportedApiVersionLog](#unsupportedapiversionlog) ` \| `[HTTPResponseLog](#httpresponselog)`\|`[HTTPRetryLog](#httpretrylog)`) => void` | A logger function that accepts [log content objects](#log-content-types). This logger will be called in certain conditions with contextual information. | | ||
| customFetchApi? | `(url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response>` | A replacement `fetch` function that will be used in all client network requests. By default, the client uses `window.fetch()`. | | ||
| logger? | `(logContent:`[`UnsupportedApiVersionLog`](#unsupportedapiversionlog) ` \| `[`HTTPResponseLog`](#httpresponselog)`\|`[`HTTPRetryLog`](#httpretrylog)`) => void` | A logger function that accepts [log content objects](#log-content-types). This logger will be called in certain conditions with contextual information. | | ||
@@ -63,7 +66,7 @@ ## Client properties | ||
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| config | [AdminApiClientConfig](#adminapiclientconfig-properties) | Configuration for the client | | ||
| config | [`AdminApiClientConfig`](#adminapiclientconfig-properties) | Configuration for the client | | ||
| getHeaders | `(headers?: {[key: string]: string}) => {[key: string]: string` | Returns Admin API specific headers needed to interact with the API. If additional `headers` are provided, the custom headers will be included in the returned headers object. | | ||
| getApiUrl | `(apiVersion?: string) => string` | Returns the shop specific API url. If an API version is provided, the returned URL will include the provided version, else the URL will include the API version set at client initialization. | | ||
| fetch | `<TData>(operation: string, options?:`[AdminAPIClientRequestOptions](#adminapiclientrequestoptions-properties)`) => Promise<Response>` | Fetches data from Admin API using the provided GQL `operation` string and [AdminAPIClientRequestOptions](#adminapiclientrequestoptions-properties) object and returns the network response. | | ||
| request | `<TData>(operation: string, options?:`[AdminAPIClientRequestOptions](#adminapiclientrequestoptions-properties)`) => Promise<`[ClientResponse\<TData\>](#clientresponsetdata)`>` | Requests data from Admin API using the provided GQL `operation` string and [AdminAPIClientRequestOptions](#adminapiclientrequestoptions-properties) object and returns a normalized response object. | | ||
| fetch | `(operation: string, options?:`[`AdminAPIClientRequestOptions`](#adminapiclientrequestoptions-properties)`) => Promise<Response>` | Fetches data from Admin API using the provided GQL `operation` string and [`AdminAPIClientRequestOptions`](#adminapiclientrequestoptions-properties) object and returns the network response. | | ||
| request | `<TData>(operation: string, options?:`[`AdminAPIClientRequestOptions`](#adminapiclientrequestoptions-properties)`) => Promise<`[`ClientResponse<TData>`](#clientresponsetdata)`>` | Requests data from Admin API using the provided GQL `operation` string and [`AdminAPIClientRequestOptions`](#adminapiclientrequestoptions-properties) object and returns a normalized response object. | | ||
@@ -85,3 +88,3 @@ ## `AdminApiClientConfig` properties | ||
| -------------- | ------------------------ | ---------------------------------------------------- | | ||
| variables? | `Record<string, any>` | Variable values needed in the graphQL operation | | ||
| variables? | `{[key: string]: any}` | Variable values needed in the graphQL operation | | ||
| apiVersion? | `string` | The Admin API version to use in the API request | | ||
@@ -95,4 +98,4 @@ | headers? | `{[key: string]: string}`| Customized headers to be included in the API request | | ||
| ----------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| data? | `TData \| any` | Data returned from the Admin API. If `TData` was provided to the function, the return type is `TData`, else it returns type `any`. | | ||
| errors? | [ResponseErrors](#responseerrors) | Error object that contains any API or network errors that occured while fetching the data from the API. It does not include any `UserErrors`. | | ||
| data? | `Partial<TData> \| any` | Data returned from the Admin API. If `TData` was provided to the function, the return type is `TData`, else it returns type `any`. | | ||
| errors? | [`ResponseErrors`](#responseerrors) | Error object that contains any API or network errors that occured while fetching the data from the API. It does not include any `UserErrors`. | | ||
| extensions? | `{[key: string]: any}` | Additional information on the GraphQL response data and context. It can include the `context` object that contains the localization context information used to generate the returned API response. | | ||
@@ -107,2 +110,3 @@ | ||
| graphQLErrors? | `any[]` | The GraphQL API errors returned by the server | | ||
| response? | `Response` | The raw response object from the network fetch call | | ||
@@ -342,3 +346,3 @@ ### Client `request()` response examples | ||
| -------- | ------------------------ | ---------------------------------- | | ||
| type | `LogType['UNSUPPORTED_API_VERSION']` | The type of log content. Is always set to `UNSUPPORTED_API_VERSION` | | ||
| type | `LogType['Unsupported_Api_Version']` | The type of log content. Is always set to `Unsupported_Api_Version` | | ||
| content | `{apiVersion: string, supportedApiVersions: string[]}` | Contextual info including the provided API version and the list of currently supported API versions. | | ||
@@ -353,3 +357,3 @@ | ||
| type | `LogType['HTTP-Response']` | The type of log content. Is always set to `HTTP-Response` | | ||
| content | `{`[requestParams](#requestparams)`: [url, init?], response: Response}` | Contextual data regarding the request and received response | | ||
| content | `{`[`requestParams`](#requestparams)`: [url, init?], response: Response}` | Contextual data regarding the request and received response | | ||
@@ -363,3 +367,3 @@ ### `HTTPRetryLog` | ||
| type | `LogType['HTTP-Retry']` | The type of log content. Is always set to `HTTP-Retry` | | ||
| content | `{`[requestParams](#requestparams)`: [url, init?], lastResponse?: Response, retryAttempt: number, maxRetries: number}` | Contextual data regarding the upcoming retry attempt. <br /><br/>`requestParams`: [parameters](#requestparams) used in the request<br/>`lastResponse`: previous response <br/> `retryAttempt`: the current retry attempt count <br/> `maxRetries`: the maximum number of retries | | ||
| content | `{`[`requestParams`](#requestparams)`: [url, init?], lastResponse?: Response, retryAttempt: number, maxRetries: number}` | Contextual data regarding the upcoming retry attempt. <br /><br/>`requestParams`: [parameters](#requestparams) used in the request<br/>`lastResponse`: previous response <br/> `retryAttempt`: the current retry attempt count <br/> `maxRetries`: the maximum number of retries | | ||
@@ -372,1 +376,145 @@ ### `RequestParams` | ||
| init? | `{method?: string, headers?: HeaderInit, body?: string}` | The request information | | ||
## Using the REST API client | ||
Initialize the client: | ||
```typescript | ||
import {createAdminRestApiClient} from '@shopify/admin-api-client'; | ||
const client = createAdminRestApiClient({ | ||
storeDomain: 'your-shop-name.myshopify.com', | ||
apiVersion: '2023-04', | ||
accessToken: 'your-admin-api-access-token', | ||
}); | ||
``` | ||
Query for a product: | ||
```typescript | ||
const response = await client.get("products/1234567890"); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` | ||
### `createAdminRestApiClient()` parameters | ||
| Property | Type | Description | | ||
| ------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| storeDomain | `string` | The `myshopify.com` domain | | ||
| apiVersion | `string` | The requested Admin API version | | ||
| accessToken | `string` | The Admin API access token | | ||
| userAgentPrefix? | `string` | Any prefix you wish to include in the User-Agent for requests made by the library. | | ||
| retries? | `number` | The number of HTTP request retries if the request was abandoned or the server responded with a `Too Many Requests (429)` or `Service Unavailable (503)` response. Default value is `0`. Maximum value is `3`. | | ||
| customFetchApi? | `(url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response>` | A replacement `fetch` function that will be used in all client network requests. By default, the client uses `window.fetch()`. | | ||
| logger? | `(logContent:`[`UnsupportedApiVersionLog`](#unsupportedapiversionlog) ` \| `[`HTTPResponseLog`](#httpresponselog)`\|`[`HTTPRetryLog`](#httpretrylog)`) => void` | A logger function that accepts [log content objects](#log-content-types). This logger will be called in certain conditions with contextual information. | | ||
| scheme? | `http` \| `https` | The HTTP scheme to use for requests | | ||
| defaultRetryTime? | `number` | How long to wait for a retry when missing the `Retry-After` header | | ||
| formatPaths? | `boolean` | Whether to format paths, e.g. `products/123` => `/products/123.json` | | ||
## Client properties | ||
| Property | Type | Description | | ||
| ------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ||
| get | `(path: string, options?:`[`GetRequestOptions`](#getrequestoptions-properties)`) => Promise<Response>` | Performs a GET request to the API. | | ||
| post | `(path: string, options?:`[`PostRequestOptions`](#postrequestoptions-properties)`) => Promise<Response>` | Performs a POST request to the API. | | ||
| put | `(path: string, options?:`[`PutRequestOptions`](#putrequestoptions-properties)`) => Promise<Response>` | Performs a PUT request to the API. | | ||
| delete | `(path: string, options?:`[`DeleteRequestOptions`](#deleterequestoptions-properties)`) => Promise<Response>` | Performs a DELETE request to the API. | | ||
## `GetRequestOptions` properties | ||
| Name | Type | Description | | ||
| ------------- | --------------------------------------- | ----------------------------------------------------- | | ||
| apiVersion? | `string` | The Admin API version to use in the API request. | | ||
| headers? | `{[key: string]: string}` | Customized headers to be included in the API request. | | ||
| searchParams? | `{ [key: string]: string \| number[] }` | Any extra query string arguments to include in the request. | | ||
| retries? | `number` | Alternative number of retries for the request. Retries only occur for requests that were abandoned or if the server responds with a `Too Many Request (429)` or `Service Unavailable (503)` response. Minimum value is `0` and maximum value is `3.` | | ||
| data? | `{ [key: string]: any } \| string` | Request body data. | | ||
## `PostRequestOptions` properties | ||
Same options as for [GET requests](#getrequestoptions-properties), but `data` isn't optional. | ||
## `PutRequestOptions` properties | ||
Same options as for [POST requests](#postrequestoptions-properties). | ||
## `DeleteRequestOptions` properties | ||
Same options as for [GET requests](#getrequestoptions-properties). | ||
## Usage examples | ||
### Query for a product | ||
```typescript | ||
const response = await client.get("products/1234567890"); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` | ||
### Update a product | ||
```typescript | ||
const response = await client.put("products/1234567890", | ||
{ | ||
data: { | ||
product: { | ||
handle: "my-new-handle", | ||
} | ||
} | ||
} | ||
); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` | ||
### Dynamically set the Admin API version per data fetch | ||
```typescript | ||
const response = await client.get("products/1234567890", | ||
{ | ||
apiVersion: '2023-01', | ||
} | ||
); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` | ||
### Add custom headers to API request | ||
```typescript | ||
const response = await client.get("products/1234567890", | ||
{ | ||
headers: { | ||
'X-My-Custom-Header': "1", | ||
}, | ||
} | ||
); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` | ||
### Dynamically set the number of retries per request | ||
```typescript | ||
const response = await client.get("products/1234567890", | ||
{ | ||
retries: 2, | ||
} | ||
); | ||
if (response.ok) { | ||
const body = await response.json(); | ||
} | ||
``` |
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
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
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
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
192239
76
1254
511
13
+ Added@shopify/graphql-client@0.9.4(transitive)
- Removed@shopify/graphql-client@0.8.0(transitive)