Skip to content

Commit

Permalink
v3 released ! more optimized response parsing and extra cookie config…
Browse files Browse the repository at this point in the history
…urations added! beside that handled undefined body and headers edge case!
  • Loading branch information
ToxicalNoob3062 committed Apr 8, 2024
1 parent 5b4142f commit e493baa
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 33 deletions.
Binary file modified bun.lockb
Binary file not shown.
23 changes: 23 additions & 0 deletions fetch-parse.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
declare module "fetch-parse" {
type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
type Parser = (res: Response) => Promise<any>;
type Parsers = { [type: string]: true | Parser };

function fetchParse(fetch: Fetch, types?: Parsers): Fetch;

namespace fetchParse {
function fetch(
fetch: Fetch,
types: Parsers,
url: RequestInfo,
opts?: RequestInit
): Promise<Response>;
function parse(types: Parsers, res: Response): Promise<Response>;
function arrayBuffer(res: Response): Promise<ArrayBuffer>;
function text(res: Response): Promise<string>;
function json(res: Response): Promise<any>;
function set(res: Response, body: any): Response;
}

export = fetchParse;
}
2 changes: 1 addition & 1 deletion index.js

Large diffs are not rendered by default.

3 changes: 0 additions & 3 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,6 @@ describe("fetchAdapter", () => {
q: "John",
},
});

console.log(res.data);

expect(res.status).toBeGreaterThanOrEqual(200);
expect(res.status).toBeLessThan(300);
expect(res.headers["content-type"]).toContain("application/json");
Expand Down
59 changes: 32 additions & 27 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,37 @@
import fetchParse from "fetch-parse";
import {
AxiosError,
type AxiosAdapter,
type AxiosPromise,
type AxiosRequestHeaders,
type AxiosResponse,
type InternalAxiosRequestConfig,
} from "axios";
("");

export type fetch = typeof fetch;

function purifyHeaders(headers: AxiosRequestHeaders): Record<string, string> {
const headersObj: Record<string, string> = {};
for (const key in headers) {
if (headers[key] !== undefined) {
headersObj[key] = headers[key];
}
}
return headersObj;
}

// Axios adapter that can take any fetch implementation
export default function (fetch: fetch): AxiosAdapter {
fetch = fetchParse(fetch);
//return the adapter using that fetch implementation
return async (config: InternalAxiosRequestConfig): AxiosPromise => {
//get the url from the config
let url = (config.baseURL ? config.baseURL : "") + config.url;
const url = new URL(config.url!, config.baseURL);
//append params to the url if they exist
if (config.params) {
const params = new URLSearchParams(config.params).toString();
url += "?" + params;
}
if (!url) {
throw new AxiosError(
"no url specified. @fetchAdapter",
"777 (FETCH_ERROR)",
config
Object.keys(config.params).forEach((key) =>
url.searchParams.append(key, config.params[key])
);
}

Expand All @@ -33,17 +41,23 @@ export default function (fetch: fetch): AxiosAdapter {
//let request object
const requestOptions: RequestInit = {
method: config.method,
headers: config.headers,
body: config.data,
body: config.data == undefined ? null : config.data,
headers: purifyHeaders(config.headers),
credentials: config.withCredentials ? "include" : "same-origin",
};

//create the request object to refer
const request = new Request(url, requestOptions);
const request = new Request(url.toString(), requestOptions);

//fetch the data
let response: Response;
try {
response = await fetch(url, requestOptions);
response = (await Promise.race([
fetch(url.toString(), requestOptions),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("timeout")), 5000)
),
])) as Response;

response.headers.forEach((value, name) => {
headers[name] = value;
Expand All @@ -52,7 +66,7 @@ export default function (fetch: fetch): AxiosAdapter {
//if response is not ok, throw an error
if (!response.ok) {
const responseObj: AxiosResponse = {
data: await response.text(),
data: response.body,
status: response.status,
statusText: response.statusText,
headers: headers,
Expand All @@ -72,27 +86,18 @@ export default function (fetch: fetch): AxiosAdapter {

//if the error is not something we can handle, throw a generic error
throw new AxiosError(
"an error occurred while making the request.(" +
err +
") @fetchAdapter",
`An error occurred while making the request. Error: ${
(err as Error).message
}`,
"777 (FETCH_ERROR)",
config,
request
);
}

//parse the response
let data;
const contentType = headers["content-type"];
if (contentType && contentType.includes("application/json")) {
data = await response.json();
} else {
data = await response.text();
}

//create the AxiosResponse object
const axiosRes: AxiosResponse = {
data,
data: response.body,
status: response.status,
statusText: response.statusText,
headers: headers,
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
{
"name": "fetchify-axios",
"description": "Fetchify Axios is a fetch adapter for Axios that takes any function that implements the standard fetchAPI interface!",
"version": "1.0.2",
"version": "1.0.3",
"main": "index.js",
"module": "index.js",
"types": "index.ts",
"repository": {
"type": "git",
"url": "https://github.com/ToxicalNoob3062/fetchify-axios.git"
},
"dependencies": {
"fetch-parse": "^1.1.0"
},
"devDependencies": {
"@types/bun": "latest",
"axios": "^1.6.8"
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
},
"include": ["index.ts"]
"include": ["index.ts", "fetch-parse.d.ts"]
}

0 comments on commit e493baa

Please sign in to comment.