Skip to content

Commit

Permalink
feat: add onError handler to apiClient
Browse files Browse the repository at this point in the history
  • Loading branch information
greeeg committed Jan 1, 2024
1 parent 4eb2a2d commit 12dba37
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const apiClient = getAPIClient({
headers: {
Accept: 'application/json',
},
onError: (statusCode: number, response: Response) => {
console.log(`[network-error]: ${statusCode} status code`, response)
},
})

const response = await apiClient.showPetById({
Expand Down
3 changes: 3 additions & 0 deletions packages/openapi-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const apiClient = getAPIClient({
headers: {
Accept: 'application/json',
},
onError: (statusCode: number, response: Response) => {
console.log(`[network-error]: ${statusCode} status code`, response)
},
})

const response = await apiClient.showPetById({
Expand Down
2 changes: 2 additions & 0 deletions packages/openapi-kit/src/generators/apiClient/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export const buildFunction = ({
` )`,
` const data = await response.json().catch(() => null)`,
` if (!response.ok) {`,
` onError?.(response.status, response)`,
` return {`,
` ok: false,`,
` statusCode: response.status,`,
Expand Down Expand Up @@ -99,6 +100,7 @@ export const getHeaderLines = (typeDefinitionsImportPath: string) => [
``,
`export interface APIClientConfig extends Omit<RequestInit, "method"> {`,
` baseUrl: string;`,
` onError?: (statusCode: number, response: Response) => void;`,
`}`,
``,
`const createPath = (path: string, pathParams?: object): string => {`,
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-kit/src/generators/apiClient/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const generateAPIClient = async (

lines.push(
`export const getAPIClient = (config: APIClientConfig) => {`,
` const { baseUrl, headers, ...configRest } = config;`,
` const { baseUrl, headers, onError, ...configRest } = config;`,
)

operations.forEach((operation) => {
Expand Down

0 comments on commit 12dba37

Please sign in to comment.