forked from VladislavPixel/home-work-cs-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-class.ts
76 lines (59 loc) · 1.83 KB
/
fetch-class.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Fetch {
static methodSave: string = "GET";
static urlSave: string = "";
static querySave: Record<string, any> = {};
static contentTypeSave: string = "application/json";
static bodySave: any = null;
static method(methodName: string): typeof Fetch {
return class extends this {
static override methodSave: string = methodName;
};
};
static url(urlStr: string): typeof Fetch {
return class extends this {
static override urlSave: string = urlStr;
};
};
static query(key: string, value: any): typeof Fetch {
const newQueryStore: Record<string, any> = {...this.querySave, [key]: value};
return class extends this {
static override querySave: Record<string, any> = newQueryStore;
};
};
static body(contentType: string, data: any): typeof Fetch {
return class extends this {
static override contentTypeSave: string = contentType;
static override bodySave: any = data;
};
};
static send(): Promise<Response> {
return new Promise((resolve, reject) => {
if (this.urlSave === "") {
reject(new Error("Your url is not correct!"));
}
const url = this.urlSave + (Object.keys(this.querySave).length !== 0 ? "?" + new URLSearchParams(this.querySave).toString() : "");
if (this.bodySave === null || this.bodySave === undefined || this.methodSave === "GET") {
console.log("ЗАПРОС В GET");
resolve(fetch(url, { method: this.methodSave }));
} else {
resolve(fetch(url, {
method: this.methodSave,
headers: {
"Content-Type": this.contentTypeSave
},
body: JSON.stringify(this.bodySave)
}));
}
});
};
};
//const myUrlReq = Fetch
// .method("GET")
// .url("https://jsonplaceholder.typicode.com/comments");
//myUrlReq
// .query("postId", 1)
// .send()
// .then((data) => {
// console.log(data, "Данные пришли");
// });
export { Fetch };