Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
umutozel committed Feb 16, 2025
1 parent 6250bae commit 5599222
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions lib/fetch-provider.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import { AjaxOptions, AjaxResponse, IAjaxProvider, mergeAjaxOptions, Value } from "jinqu";
import { AjaxOptions, AjaxResponse, IAjaxProvider, Value } from "jinqu";

export class FetchProvider implements IAjaxProvider<Response> {
export type FetchOptions = AjaxOptions & RequestInit;

public static readonly defaultOptions: AjaxOptions = {
export class FetchProvider implements IAjaxProvider<Response, FetchOptions> {

public static readonly defaultOptions: FetchOptions = {
$headers: {
"Accept": "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8",
},
$method: "GET",
};

public ajax<T>(o: AjaxOptions): Promise<Value<T> & AjaxResponse<Response>> {
public ajax<T>(o: FetchOptions): Promise<Value<T> & AjaxResponse<Response>> {
if (o.$params && o.$params.length) {
o.$url += "?" + o.$params.map(p => `${p.key}=${encodeURIComponent(p.value)}`).join("&");
}

const promise = fetch(o.$url, createRequest(o))
.then(r => {
return r.json()
.then(d => ({ value: d, response: r }));
.then(async r => {
let d = await r.json();
return ({ value: d, response: r });
});

if (!o.$timeout)
Expand All @@ -33,13 +35,17 @@ export class FetchProvider implements IAjaxProvider<Response> {
}
}

export function createRequest(o: AjaxOptions) {
const d = Object.assign({}, FetchProvider.defaultOptions);
o = mergeAjaxOptions(d, o);
export function createRequest(o: FetchOptions) {
const oo = Object.assign({}, FetchProvider.defaultOptions, o);
const ao = Object.fromEntries(Object.entries(oo).filter(([key]) => key[0] != "$"));

ao.method = ao.method || oo.$method;
if (oo.$data != null && oo.$method != "GET") {
ao.body = JSON.stringify(oo.$data);
}
if (oo.$headers != null) {
ao.headers = Object.assign(ao.headers || {}, oo.$headers);
}

return {
body: o.$method === "GET" ? void 0 : o.$data,
headers: o.$headers,
method: o.$method,
} as RequestInit;
return ao;
}

0 comments on commit 5599222

Please sign in to comment.