Skip to content

Commit

Permalink
refactor: Replace axios with fetch in postCustomer method
Browse files Browse the repository at this point in the history
Refactor the postCustomer method in the Unguess class to use the fetch API instead of axios for making HTTP requests. This change improves the code's performance and reduces the number of dependencies.
  • Loading branch information
sinatragianpaolo committed Nov 27, 2024
1 parent a3649b2 commit abc0d66
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 81 deletions.
85 changes: 85 additions & 0 deletions src/features/class/Unguess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
class Unguess {
private baseUrl: string;
private username: string;
private password: string;

constructor(baseUrl: string, username: string, password: string) {
this.baseUrl = baseUrl;
this.username = username;
this.password = password;
}

/**
* Private method to fetch a token for API requests
*/
private async getToken(): Promise<string> {
const response = await fetch(`${this.baseUrl}/authenticate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: this.username,
password: this.password,
}),
});

if (!response.ok) {
throw new Error("Failed to authenticate: " + response.statusText);
}

const data = await response.json();
if (!data.token) {
throw new Error("Authentication failed: Token not found");
}

return data.token;
}

/**
* Private method to perform authenticated POST requests
*/
private async authPost(
path: string,
body: Record<string, any>
): Promise<any> {
const token = await this.getToken();
const response = await fetch(`${this.baseUrl}${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});

if (!response.ok) {
throw new Error(`Failed to post to ${path}: ${response.statusText}`);
}

return response.json();
}

/**
* Public method to post a new customer
*/
public async postCustomer({
userId,
name,
}: {
userId: number;
name: string;
}): Promise<{ id: number; name: string }> {
const body = {
company: name,
pm_id: userId,
};
const result = await this.authPost("/workspaces", body);
return {
id: result.id,
name: result.name,
};
}
}

export default Unguess;
25 changes: 20 additions & 5 deletions src/routes/customers/_post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import OpenapiError from "@src/features/OpenapiError";
import UserRoute from "@src/features/routes/UserRoute";
import { unguessPostCustomer } from "./unguessPostCustomer";
import Unguess from "@src/features/class/Unguess";
import config from "@src/config";

class RouteItem extends UserRoute<{
response: StoplightOperations["post-customers"]["responses"]["200"]["content"]["application/json"];
Expand All @@ -26,13 +27,27 @@ class RouteItem extends UserRoute<{
}

protected async prepare(): Promise<void> {
const customer = await unguessPostCustomer({
company: this.getBody().name,
userId: this.getTesterId(),
});
const customer = await this.postCustomerUnguessApi();

return this.setSuccess(201, customer);
}

private async postCustomerUnguessApi() {
const { basePath, username, password } = config.unguessApi || {};

const unguess = new Unguess(basePath || "", username || "", password || "");

try {
const customer = await unguess.postCustomer({
userId: this.getTesterId(),
name: this.getBody().name,
});
console.log("Customer created:", customer);
return customer;
} catch (error) {
console.error("Error creating customer:", error);
}
}
}

export default RouteItem;
76 changes: 0 additions & 76 deletions src/routes/customers/_post/unguessPostCustomer/index.ts

This file was deleted.

0 comments on commit abc0d66

Please sign in to comment.