Skip to content
This repository was archived by the owner on Oct 11, 2024. It is now read-only.

Commit dc758b9

Browse files
authored
refactor(util): use fetch instead of axios for HTTP requests (#68)
* build(deps): remove axios * refactor(http): use fetch instead of axios for HTTP requests
1 parent 950a53a commit dc758b9

File tree

4 files changed

+106
-81
lines changed

4 files changed

+106
-81
lines changed

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,6 @@
434434
]
435435
},
436436
"dependencies": {
437-
"axios": "^1.6.7",
438437
"clipboardy": "^4.0.0",
439438
"marked": "^12.0.0",
440439
"node-machine-id": "^1.1.12",

src/util/github.ts

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
// See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0> for full license details.
55

66
import * as vscode from "vscode";
7-
import axios, { AxiosResponse } from "axios";
87
import { getCurrentRepoName } from "./session";
98

109
export interface GitHubRepo {
@@ -25,19 +24,16 @@ interface GithubUser {
2524
login: string;
2625
}
2726

28-
export async function getUser(githubtoken: string): Promise<GithubUser> {
27+
export async function getUser(githubToken: string): Promise<GithubUser> {
2928
try {
3029
// Check that it's a public repo
31-
const response: AxiosResponse<any> = await axios.get(
32-
`https://api.github.com/user`,
33-
{
34-
headers: { Authorization: `Bearer ${githubtoken}` },
35-
},
36-
);
30+
const response = await fetch(`https://api.github.com/user`, {
31+
headers: { Authorization: `Bearer ${githubToken}` },
32+
});
3733

3834
// Handle the response
39-
if (response.status === 200) {
40-
return response.data;
35+
if (response.ok) {
36+
return (await response.json()) as GithubUser;
4137
} else {
4238
// The request returned a non-200 status code (e.g., 404)
4339
// Show an error message or handle the error accordingly
@@ -64,14 +60,13 @@ export async function getRepoDetails(
6460
): Promise<GitHubRepo> {
6561
try {
6662
// Check that it's a public repo
67-
const response: AxiosResponse<any> = await axios.get(
68-
`https://api.github.com/repos/${repoName}`,
69-
{ headers: { Authorization: `Bearer ${githubToken}` } },
70-
);
63+
const response = await fetch(`https://api.github.com/repos/${repoName}`, {
64+
headers: { Authorization: `Bearer ${githubToken}` },
65+
});
7166

7267
// Handle the response
73-
if (response.status === 200) {
74-
return response.data;
68+
if (response.ok) {
69+
return (await response.json()) as GitHubRepo;
7570
} else {
7671
throw new Error(`GitHub API returned status code ${response.status}`);
7772
}

src/util/quack.ts

Lines changed: 94 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
// See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0> for full license details.
55

66
import * as vscode from "vscode";
7-
import axios, { AxiosResponse, AxiosError } from "axios";
87

98
let config = vscode.workspace.getConfiguration("api");
109

@@ -40,6 +39,10 @@ export interface StreamingMessage {
4039
done: boolean;
4140
}
4241

42+
interface QuackToken {
43+
access_token: string;
44+
}
45+
4346
export async function verifyQuackEndpoint(
4447
endpointURL: string,
4548
): Promise<boolean> {
@@ -48,14 +51,15 @@ export async function verifyQuackEndpoint(
4851
endpointURL,
4952
).toString();
5053
try {
51-
await axios.get(routeURL);
52-
return true;
53-
} catch (error) {
54-
if (error instanceof AxiosError) {
55-
if (error.response && error.response.status === 401) {
56-
return true;
57-
}
54+
const response = await fetch(routeURL);
55+
if (response.ok) {
56+
return true;
57+
} else if (response.status === 401) {
58+
return true;
59+
} else {
60+
return false;
5861
}
62+
} catch (error) {
5963
return false;
6064
}
6165
}
@@ -69,19 +73,21 @@ export async function getAPIAccessStatus(
6973
endpointURL,
7074
).toString();
7175
try {
72-
await axios.get(routeURL, {
76+
const response = await fetch(routeURL, {
7377
headers: { Authorization: `Bearer ${quackToken}` },
7478
});
75-
return "ok"; // Token & endpoint good
79+
if (response.ok) {
80+
return "ok"; // Token & endpoint good
81+
} else if (response.status === 404) {
82+
return "unknown-route"; // Unknown route
83+
} else if (response.status === 401) {
84+
return "expired-token"; // Expired token
85+
} else {
86+
return "other"; // Other HTTP status codes
87+
}
7688
} catch (error) {
77-
if (error instanceof AxiosError) {
78-
if (error.code === "ECONNREFUSED") {
79-
return "unreachable-endpoint"; // Wrong endpoint
80-
} else if (error.response && error.response.status === 404) {
81-
return "unknown-route"; // Unknown route
82-
} else if (error.response && error.response.status === 401) {
83-
return "expired-token"; // expired
84-
}
89+
if (error instanceof Error && error.name === "TypeError") {
90+
return "unreachable-endpoint"; // Wrong endpoint
8591
}
8692
return "other"; // Token or server issues
8793
}
@@ -115,13 +121,20 @@ export async function getToken(
115121
const quackURL = new URL("/api/v1/login/token", endpointURL).toString();
116122
try {
117123
// Retrieve the guidelines
118-
const response: AxiosResponse<any> = await axios.post(quackURL, {
119-
github_token: githubToken,
124+
const response = await fetch(quackURL, {
125+
method: "POST",
126+
headers: {
127+
"Content-Type": "application/json",
128+
},
129+
body: JSON.stringify({
130+
github_token: githubToken,
131+
}),
120132
});
121133

122134
// Handle the response
123-
if (response.status === 200) {
124-
return response.data.access_token;
135+
if (response.ok) {
136+
const data = (await response.json()) as QuackToken;
137+
return data.access_token;
125138
} else {
126139
// The request returned a non-200 status code (e.g., 404)
127140
// Show an error message or handle the error accordingly
@@ -149,13 +162,13 @@ export async function fetchGuidelines(
149162
const quackURL = new URL(`/api/v1/guidelines`, endpointURL).toString();
150163
try {
151164
// Retrieve the guidelines
152-
const response: AxiosResponse<any> = await axios.get(quackURL, {
165+
const response = await fetch(quackURL, {
153166
headers: { Authorization: `Bearer ${token}` },
154167
});
155168

156169
// Handle the response
157-
if (response.status === 200) {
158-
return response.data;
170+
if (response.ok) {
171+
return (await response.json()) as QuackGuideline[];
159172
} else {
160173
// The request returned a non-200 status code (e.g., 404)
161174
// Show an error message or handle the error accordingly
@@ -185,24 +198,36 @@ export async function postChatMessage(
185198
): Promise<void> {
186199
const quackURL = new URL("/api/v1/code/chat", endpointURL).toString();
187200
try {
188-
const response: AxiosResponse<any> = await axios.post(
189-
quackURL,
190-
{ messages: messages },
191-
{ headers: { Authorization: `Bearer ${token}` }, responseType: "stream" },
192-
);
193-
response.data.on("data", (chunk: any) => {
194-
// Handle the chunk of data
195-
onChunkReceived(JSON.parse(chunk).message.content);
196-
});
197-
198-
response.data.on("end", () => {
199-
// console.log("Stream ended");
200-
onEnd();
201+
const response = await fetch(quackURL, {
202+
method: "POST",
203+
headers: {
204+
"Content-Type": "application/json",
205+
Authorization: `Bearer ${token}`,
206+
},
207+
body: JSON.stringify({ messages: messages }),
201208
});
202209

203-
response.data.on("error", (error: Error) => {
204-
console.error(error);
205-
});
210+
if (response.body) {
211+
const reader = response.body.getReader();
212+
try {
213+
while (true) {
214+
const { done, value } = await reader.read();
215+
if (done) {
216+
break;
217+
}
218+
// Assume each chunk is a Uint8Array, convert to a string or otherwise process
219+
const chunk = new TextDecoder().decode(value);
220+
// Process the chunk, e.g., assuming JSON content
221+
onChunkReceived(JSON.parse(chunk).message.content);
222+
}
223+
// Stream ended
224+
onEnd();
225+
} catch (error) {
226+
console.error(error);
227+
} finally {
228+
reader.releaseLock();
229+
}
230+
}
206231
} catch (error) {
207232
// Handle other errors that may occur during the request
208233
console.error("Error sending Quack API request:", error);
@@ -219,17 +244,18 @@ export async function postGuideline(
219244
const quackURL = new URL(`/api/v1/guidelines`, endpointURL).toString();
220245
try {
221246
// Retrieve the guidelines
222-
const response: AxiosResponse<any> = await axios.post(
223-
quackURL,
224-
{ content: content },
225-
{
226-
headers: { Authorization: `Bearer ${token}` },
247+
const response = await fetch(quackURL, {
248+
method: "POST",
249+
headers: {
250+
"Content-Type": "application/json",
251+
Authorization: `Bearer ${token}`,
227252
},
228-
);
253+
body: JSON.stringify({ content: content }),
254+
});
229255

230256
// Handle the response
231-
if (response.status === 201) {
232-
return response.data;
257+
if (response.ok) {
258+
return (await response.json()) as QuackGuideline;
233259
} else {
234260
vscode.window.showErrorMessage(
235261
`Quack API returned status code ${response.status}`,
@@ -254,18 +280,19 @@ export async function patchGuideline(
254280
): Promise<QuackGuideline> {
255281
const quackURL = new URL(`/api/v1/guidelines/${id}`, endpointURL).toString();
256282
try {
257-
// Retrieve the guidelines
258-
const response: AxiosResponse<any> = await axios.patch(
259-
quackURL,
260-
{ content: content },
261-
{
262-
headers: { Authorization: `Bearer ${token}` },
283+
// Update the guideline
284+
const response = await fetch(quackURL, {
285+
method: "PATCH",
286+
headers: {
287+
"Content-Type": "application/json",
288+
Authorization: `Bearer ${token}`,
263289
},
264-
);
290+
body: JSON.stringify({ content: content }),
291+
});
265292

266293
// Handle the response
267-
if (response.status === 200) {
268-
return response.data;
294+
if (response.ok) {
295+
return (await response.json()) as QuackGuideline;
269296
} else {
270297
vscode.window.showErrorMessage(
271298
`Quack API returned status code ${response.status}`,
@@ -289,14 +316,18 @@ export async function deleteGuideline(
289316
): Promise<QuackGuideline> {
290317
const quackURL = new URL(`/api/v1/guidelines/${id}`, endpointURL).toString();
291318
try {
292-
// Retrieve the guidelines
293-
const response: AxiosResponse<any> = await axios.delete(quackURL, {
294-
headers: { Authorization: `Bearer ${token}` },
319+
// Delete the guideline
320+
const response = await fetch(quackURL, {
321+
method: "DELETE",
322+
headers: {
323+
"Content-Type": "application/json",
324+
Authorization: `Bearer ${token}`,
325+
},
295326
});
296327

297328
// Handle the response
298-
if (response.status === 200) {
299-
return response.data;
329+
if (response.ok) {
330+
return (await response.json()) as QuackGuideline;
300331
} else {
301332
vscode.window.showErrorMessage(
302333
`Quack API returned status code ${response.status}`,

yarn.lock

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ asynckit@^0.4.0:
494494
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
495495
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
496496

497-
axios@^1.6.2, axios@^1.6.7:
497+
axios@^1.6.2:
498498
version "1.6.7"
499499
resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.7.tgz#7b48c2e27c96f9c68a2f8f31e2ab19f59b06b0a7"
500500
integrity sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==

0 commit comments

Comments
 (0)