Skip to content

Commit

Permalink
Add the ability to pass the already created axios instance in the con…
Browse files Browse the repository at this point in the history
…fig (#222)
  • Loading branch information
max-lychko authored and robinheinze committed Aug 20, 2019
1 parent 9fe855f commit fd286c1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
1 change: 1 addition & 0 deletions apisauce.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type PROBLEM_CODE =

export interface ApisauceConfig extends AxiosRequestConfig {
baseURL: string | undefined;
axiosInstance: AxiosInstance | undefined;
}

/**
Expand Down
16 changes: 11 additions & 5 deletions lib/apisauce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,19 @@ export const getProblemFromStatus = status => {
* Creates a instance of our API using the configuration.
*/
export const create = config => {
// combine the user's defaults with ours
// combine the user's headers with ours
const headers = merge(DEFAULT_HEADERS, config.headers || {})
const combinedConfig = merge(DEFAULT_CONFIG, dissoc('headers', config))

// create the axios instance
const instance = axios.create(combinedConfig)

let instance
if (config.axiosInstance) {
// use passed axios instance
instance = config.axiosInstance
} else {
const combinedConfig = merge(DEFAULT_CONFIG, dissoc('headers', config))
// create the axios instance
instance = axios.create(combinedConfig)
}

const monitors = []
const addMonitor = monitor => {
monitors.push(monitor)
Expand Down
17 changes: 14 additions & 3 deletions test/config.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import test from 'ava'
import { create, DEFAULT_HEADERS } from '../lib/apisauce'
import { merge } from 'ramda'
import axios from 'axios'

const validConfig = {
baseURL: 'http://localhost:9991',
Expand All @@ -19,8 +20,18 @@ test('returns an object when we configure correctly', t => {

test('configures axios correctly', t => {
const apisauce = create(validConfig)
const axios = apisauce.axiosInstance
t.is(axios.defaults.timeout, 0)
t.is(axios.defaults.baseURL, validConfig.baseURL)
const { axiosInstance } = apisauce
t.is(axiosInstance.defaults.timeout, 0)
t.is(axiosInstance.defaults.baseURL, validConfig.baseURL)
t.deepEqual(apisauce.headers, merge(DEFAULT_HEADERS, validConfig.headers))
})

test('configures axios correctly with passed instance', t => {
const customAxiosInstance = axios.create({ baseURL: validConfig.baseURL })
const apisauce = create({ axiosInstance: customAxiosInstance, headers: validConfig.headers })
const { axiosInstance } = apisauce
t.is(axiosInstance.defaults.timeout, 0)
t.is(axiosInstance.defaults.baseURL, validConfig.baseURL)
t.deepEqual(apisauce.headers, merge(DEFAULT_HEADERS, validConfig.headers))
})

0 comments on commit fd286c1

Please sign in to comment.