Skip to content

Commit

Permalink
refactor: create api client helpers to reuse constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyentoanit committed Mar 9, 2021
1 parent 51d4a46 commit a3b90b0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 20 deletions.
24 changes: 4 additions & 20 deletions src/clients/uploads-api-client.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,20 @@
import { amazonMarketplaces } from '@scaleleap/amazon-marketplaces'
import globalAxios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios'

import { UploadsApi } from '../api-models/uploads-api-model'
import { apiErrorFactory } from '../helpers'
import { ApiClientHelpers } from '../helpers'
import { isJsonMime } from '../helpers/is-json-mime'
import { APIConfigurationParameters } from '../types/api-configuration-parameters'

export class UploadsApiClient extends UploadsApi {
constructor(parameters?: APIConfigurationParameters) {
const { sellingPartner } = amazonMarketplaces.US
const basePath: string = sellingPartner ? sellingPartner.region.endpoint : ''
let axiosInstance: AxiosInstance

if (parameters && parameters.axios) {
axiosInstance = parameters.axios
} else {
axiosInstance = globalAxios.create()
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response.data,
(error: AxiosError) => {
throw apiErrorFactory(error)
},
)
}
const axios = ApiClientHelpers.assertAxiosInstance(parameters)
const basePath = ApiClientHelpers.assertBasePath()

super(
{
isJsonMime,
...parameters,
},
basePath,
axiosInstance,
axios,
)
}
}
30 changes: 30 additions & 0 deletions src/helpers/api-client-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { amazonMarketplaces } from '@scaleleap/amazon-marketplaces'
import globalAxios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios'

import { APIConfigurationParameters } from '../types'
import { apiErrorFactory } from './api-error-factory'

export class ApiClientHelpers {
static assertAxiosInstance(parameters?: APIConfigurationParameters): AxiosInstance {
let axiosInstance: AxiosInstance

if (parameters && parameters.axios) {
axiosInstance = parameters.axios
} else {
axiosInstance = globalAxios.create()
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response.data,
(error: AxiosError) => {
throw apiErrorFactory(error)
},
)
}

return axiosInstance
}

static assertBasePath(): string {
const { sellingPartner } = amazonMarketplaces.US
return sellingPartner ? sellingPartner.region.endpoint : ''
}
}
1 change: 1 addition & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './api-client-helpers'
export * from './api-error-factory'
export * from './decoder'
export * from './is-json-mime'

0 comments on commit a3b90b0

Please sign in to comment.