Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response type blob arrarybuffer #14

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

## Intro

A lite request lib based on **fetch** with plugins support.
A lite request lib based on **fetch** with plugin support and similar API to axios.

**Features:**

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "xior",
"version": "0.3.12",
"description": "A lite request lib based on fetch with plugins support, and axios similar API",
"description": "A lite request lib based on fetch with plugin support and similar API to axios.",
"repository": "suhaotian/xior",
"bugs": "https://github.com/suhaotian/xior/issues",
"homepage": "https://github.com/suhaotian/xior",
Expand Down
17 changes: 17 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,20 @@ export type XiorPlugin = (
adapter: (request: XiorRequestConfig) => Promise<XiorResponse>,
instance?: XiorInstance
) => (request: XiorRequestConfig) => Promise<XiorResponse<any>>;

export interface XiorInterceptorOptions {
/** @deprecated useless here */
synchronous?: boolean;
/** @deprecated useless here */
runWhen?: (config: XiorInterceptorRequestConfig) => boolean;
}

export interface XiorResponseInterceptorConfig<T = any> {
data: T;
config: XiorInterceptorRequestConfig<T>;
request: XiorInterceptorRequestConfig<T>;
response: Response;
status: number;
statusText: string;
headers: Headers;
}
184 changes: 77 additions & 107 deletions src/xior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,39 @@ import {

import defaultRequestInterceptor from './interceptors';
import type {
XiorInterceptorOptions,
XiorInterceptorRequestConfig,
XiorPlugin,
XiorRequestConfig,
XiorResponse,
XiorResponseInterceptorConfig,
} from './types';

const supportAbortController = typeof AbortController !== 'undefined';

const undefinedValue = undefined;
export type XiorInstance = xior;

async function getData(
response: Response,
responseType?: 'json' | 'text' | 'stream' | 'document' | 'arraybuffer' | 'blob' | 'original'
) {
let data: any;
if (!responseType || !response.ok || ['text', 'json'].includes(responseType)) {
data = await response.text();
if (data && responseType !== 'text') {
try {
data = JSON.parse(data);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e) {}
}
} else if (responseType === 'blob') {
data = await response.blob();
} else if (responseType === 'arraybuffer') {
data = await response.arrayBuffer();
}
return data;
}

export class xior {
static create(options?: XiorRequestConfig): XiorInstance {
return new xior(options);
Expand All @@ -45,25 +68,10 @@ export class xior {
) => Promise<XiorInterceptorRequestConfig> | XiorInterceptorRequestConfig)[] = [];
/** response interceptors */
RESI: {
fn: (config: {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}) =>
| Promise<{
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}>
| {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
};
onRejected?: (error: XiorError) => any;
fn: (
config: XiorResponseInterceptorConfig
) => Promise<XiorResponseInterceptorConfig> | XiorResponseInterceptorConfig;
onRejected?: null | ((error: XiorError) => any);
}[] = [];

get interceptors() {
Expand All @@ -74,7 +82,8 @@ export class xior {
config: XiorInterceptorRequestConfig
) => Promise<XiorInterceptorRequestConfig> | XiorInterceptorRequestConfig,
/** @deprecated useless here */
onRejected?: (error: any) => any
onRejected?: null | ((error: any) => any),
options?: XiorInterceptorOptions
) => {
this.REQI.push(fn);
return fn;
Expand All @@ -92,48 +101,18 @@ export class xior {
},
response: {
use: (
fn: (config: {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}) =>
| Promise<{
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}>
| {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
},
onRejected?: (error: XiorError) => any
fn: (
config: XiorResponseInterceptorConfig
) => Promise<XiorResponseInterceptorConfig> | XiorResponseInterceptorConfig,
onRejected?: null | ((error: XiorError) => any)
) => {
this.RESI.push({ fn, onRejected });
return fn;
},
eject: (
fn: (config: {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}) =>
| Promise<{
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}>
| {
data: any;
config: XiorInterceptorRequestConfig;
request: XiorInterceptorRequestConfig;
response: Response;
}
fn: (
config: XiorResponseInterceptorConfig
) => Promise<XiorResponseInterceptorConfig> | XiorResponseInterceptorConfig
) => {
this.RESI = this.RESI.filter((item) => item.fn !== fn);
},
Expand Down Expand Up @@ -201,7 +180,7 @@ export class xior {
/** timeout */
let signal: AbortSignal;
const signals: AbortSignal[] = [];
let timer: ReturnType<typeof setTimeout> | undefined = undefined;
let timer: ReturnType<typeof setTimeout> | undefined = undefinedValue;
if (timeout && supportAbortController) {
const controller = new AbortController();
timer = setTimeout(() => {
Expand All @@ -224,21 +203,29 @@ export class xior {
finalURL = joinPath(requestConfig.baseURL, finalURL);
}

const handleResponseRejects = async (error: XiorError) => {
let hasReject = false;
for (const item of this.RESI) {
if (item.onRejected) {
hasReject = true;
const res = await item.onRejected(error);
if (res?.response?.ok) return res;
}
}
if (!hasReject) throw error;
};

let response: Response;
try {
response = await fetch(finalURL, {
body: isGet ? undefined : _data,
body: isGet ? undefinedValue : _data,
...rest,
signal,
method,
headers,
});
} catch (e) {
for (const item of this.RESI) {
if (item.onRejected) {
await item.onRejected(e as XiorError);
}
}
await handleResponseRejects(e as XiorError);
throw e;
} finally {
if (timer) clearTimeout(timer);
Expand All @@ -252,15 +239,10 @@ export class xior {
statusText: response.statusText,
headers: response.headers,
};
const { responseType } = requestConfig;
if (!response.ok) {
let data: any = undefined;
try {
data = await response.text();
if (data) {
data = JSON.parse(data);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e) {}
const data = await getData(response, responseType);

const error = new XiorError(
!response.status ? `Network error` : `Request failed with status code ${response.status}`,
requestConfig,
Expand All @@ -269,57 +251,45 @@ export class xior {
...commonRes,
}
);
for (const item of this.RESI) {
if (item.onRejected) {
const res = await item.onRejected(error);
if (res?.response?.ok) return res;
}
}
await handleResponseRejects(error);
throw error;
}

if (method === 'HEAD') {
return {
data: undefined as T,
data: undefinedValue as T,
request: requestConfig,
...commonRes,
};
}

const { responseType } = requestConfig;
if (!responseType || ['json', 'text'].includes(responseType)) {
let data: any;
try {
data = (await response.text()) as T;
if (data && responseType !== 'text') {
data = JSON.parse(data as string);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e) {
//
}
let responseObj = {
data: data as T,
const result = await getData(response, responseType);

try {
let lastRes = {
...commonRes,
data: result as T,
config: requestConfig as XiorInterceptorRequestConfig,
request: requestConfig as XiorInterceptorRequestConfig,
response,
};

for (const item of this.RESI) {
responseObj = await item.fn(responseObj);
// eslint-disable-next-line no-inner-declarations
async function run() {
return item.fn(lastRes);
}
const res = await run().catch(async (error) => {
await handleResponseRejects(error as XiorError);
});
if (res) {
lastRes = res;
}
}
return {
data: responseObj.data,
request: requestConfig,
...commonRes,
};
return lastRes;
} catch (error) {
await handleResponseRejects(error as XiorError);
throw error;
}

return {
data: undefined as T,
request: requestConfig,
...commonRes,
};
}

/** create get method */
Expand Down
47 changes: 47 additions & 0 deletions tests/src/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,53 @@ describe('xior tests', () => {
});
});

describe('`responseType` should work', () => {
it('should work with `responseType: "blob"`', async () => {
const xiorInstance = xior.create({ baseURL });
const { data: getData } = await xiorInstance.get<Blob>('/get', {
responseType: 'blob',
});
assert.strictEqual(getData instanceof Blob, true);

const { data: postData } = await xiorInstance.post<Blob>(
'/post',
{},
{ responseType: 'blob' }
);
assert.strictEqual(postData instanceof Blob, true);
});

it('should work with `responseType: "arraybuffer"`', async () => {
const xiorInstance = xior.create({ baseURL });
const { data: getData } = await xiorInstance.get<ArrayBuffer>('/get', {
responseType: 'arraybuffer',
});
assert.strictEqual(getData instanceof ArrayBuffer, true);

const { data: postData } = await xiorInstance.post<ArrayBuffer>(
'/post',
{},
{ responseType: 'arraybuffer' }
);
assert.strictEqual(postData instanceof ArrayBuffer, true);
});

it('should work with as expected `responseType: "original"` or `responseType: "stream"`', async () => {
const xiorInstance = xior.create({ baseURL });
const { data: getData } = await xiorInstance.get<ArrayBuffer>('/get', {
responseType: 'original',
});
assert.strictEqual(getData === undefined, true);

const { data: postData } = await xiorInstance.post<ArrayBuffer>(
'/post',
{},
{ responseType: 'stream' }
);
assert.strictEqual(postData === undefined, true);
});
});

describe('custom plugins should work', () => {
it('should work with custom plugin', async () => {
const xiorInstance = xior.create({ baseURL });
Expand Down
Loading
Loading