Skip to content

Commit

Permalink
feat: add defaults support to compatible axios
Browse files Browse the repository at this point in the history
  • Loading branch information
suhaotian committed Mar 9, 2024
1 parent 5027a3f commit 7d9e91a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/tests/axios-compatible.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,26 @@ describe('axios compatible tests', () => {
assert.strictEqual(data.slice(-10), axiorData?.slice(-10));
});

it('should work with `instance.defaults.* = *`', async () => {
const axiosInstance = axios.create({ baseURL });
const xiorInstance = xior.create({ baseURL });
axiosInstance.defaults.headers['x-custom-value'] = '1';
xiorInstance.defaults.headers['x-custom-value'] = '1';
if (!axiosInstance.defaults.params) {
axiosInstance.defaults.params = {};
}
axiosInstance.defaults.params['x-2'] = '2';
xiorInstance.defaults.params['x-2'] = '2';

const { data } = await axiosInstance.get('/get');
const { data: axiorData } = await xiorInstance.get('/get');
assert.strictEqual(data.value, '1');
assert.strictEqual(axiorData.value, '1');

assert.strictEqual(data.query['x-2'], '2');
assert.strictEqual(axiorData.query['x-2'], '2');
});

it('should work with params', async () => {
const axiosInstance = axios.create({ baseURL: 'https://api.github.com' });
const xiorInstance = xior.create({ baseURL: 'https://api.github.com/' });
Expand Down
7 changes: 7 additions & 0 deletions src/xior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@ export class xior {
}

config?: XiorRequestConfig;
defaults: XiorInterceptorRequestConfig;

constructor(options?: XiorRequestConfig) {
this.config = options;
this.defaults = {
params: {},
headers: {},
} as XiorInterceptorRequestConfig;
}

private requestInterceptors: ((
Expand Down Expand Up @@ -130,6 +136,7 @@ export class xior {
let requestConfig: XiorRequestConfig = merge(
{},
this.config || {},
this.defaults || {},
typeof options === 'string' ? { url: options } : options || {},
{ headers: {}, params: {} }
);
Expand Down

0 comments on commit 7d9e91a

Please sign in to comment.