Skip to content
This repository has been archived by the owner on Sep 26, 2024. It is now read-only.

Commit

Permalink
Fixes for MOC-119 and MOC-90 (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
elg0nz authored Jul 26, 2024
1 parent cfabef2 commit 6f13196
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 29 deletions.
29 changes: 22 additions & 7 deletions apps/mocksi-lite/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ chrome.action.onClicked.addListener((activeTab) => {
}

if (activeTabUrl === "" || activeTabUrl.startsWith("chrome://")) {
chrome.action.disable();
return;
}

Expand Down Expand Up @@ -293,18 +292,30 @@ async function createDemo(body: Record<string, unknown>) {
...defaultBody,
tab_id: result.id?.toString() ?? "",
url: result.url,
}).then(() => getRecordings());
})
.then(() => getRecordings())
.catch((err) => {
MocksiRollbar.error("Error creating demo", err);
});
});
}

function updateDemo(data: Record<string, unknown>) {
const { id, recording } = data;
apiCall(`recordings/${id}`, "POST", recording).then(() => getRecordings());
apiCall(`recordings/${id}`, "POST", recording)
.then(() => getRecordings())
.catch((err) => {
MocksiRollbar.error("Error updating demo", err);
});
}

async function deleteDemo(data: Record<string, unknown>) {
const { id } = data;
apiCall(`recordings/${id}`, "DELETE").then(() => getRecordings());
apiCall(`recordings/${id}`, "DELETE")
.then(() => getRecordings())
.catch((err) => {
MocksiRollbar.error("Error deleting demo", err);
});
}

async function getRecordings(): Promise<Recording[]> {
Expand All @@ -318,10 +329,14 @@ async function getRecordings(): Promise<Recording[]> {
try {
const response = await apiCall(
`recordings?creator=${encodeURIComponent(email)}`,
);
).catch((err) => {
MocksiRollbar.error(`Failed to fetch recordings: ${err}`);
chrome.storage.local.set({ recordings: "[]" });
return [];
});

if (!response || response.length === 0) {
console.error("No recordings found or failed to fetch recordings.");
MocksiRollbar.error("No recordings found.");
chrome.storage.local.set({ recordings: "[]" });
return [];
}
Expand All @@ -335,7 +350,7 @@ async function getRecordings(): Promise<Recording[]> {

return sorted;
} catch (err) {
console.error(`Failed to fetch recordings: ${err}`);
MocksiRollbar.error(`failed to fetch recordings: ${err}`);
return [];
}
}
Expand Down
3 changes: 2 additions & 1 deletion apps/mocksi-lite/common/Popup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ const Popup = ({
top: "100px",
width: "100%",
height: "75%",
zIndex: 9999999,
zIndex: 9999998,
border: "none",
};

return (
Expand Down
57 changes: 36 additions & 21 deletions apps/mocksi-lite/networking.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import auth0 from "auth0-js";
import MocksiRollbar from "./MocksiRollbar";
import { API_URL, MOCKSI_AUTH } from "./consts";

type HttpMethod = "GET" | "PUT" | "POST" | "DELETE";
Expand All @@ -18,16 +19,19 @@ const auth0Client = new auth0.WebAuth({
const getAuthToken = async (): Promise<string> => {
try {
const storageAuth = await chrome.storage.local.get(MOCKSI_AUTH);
MocksiRollbar.log("Retrieved auth from storage:", storageAuth);
const mocksiAuth = JSON.parse(storageAuth[MOCKSI_AUTH]);
MocksiRollbar.log("Parsed auth token:", mocksiAuth.accessToken);
return mocksiAuth.accessToken ?? "";
} catch (err) {
console.error("Failed to retrieve auth token:", err);
MocksiRollbar.error(`Failed to retrieve auth token: ${err}`);
return "";
}
};

const refreshToken = async (): Promise<string> => {
return new Promise((resolve, reject) => {
MocksiRollbar.log("Refreshing token");
auth0Client.checkSession(
{},
(err: auth0.Auth0Error | null, result: auth0.Auth0Result | undefined) => {
Expand Down Expand Up @@ -74,39 +78,50 @@ export const apiCall = async (
method: HttpMethod = "GET",
// biome-ignore lint/suspicious/noExplicitAny: we haven't defined the type of body yet
body?: any,
// biome-ignore lint/suspicious/noExplicitAny: we haven't defined the type of body yet
// biome-ignore lint/suspicious/noExplicitAny: we haven't defined the type of the response yet
): Promise<any> => {
try {
let token = await getAuthToken();

let res = await fetch(`${API_URL}/v1/${url}`, {
const makeRequest = async (token: string) => {
const options: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
"Accepts-Version": "v1",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
};

if (body && (method === "POST" || method === "PUT")) {
options.body = JSON.stringify(body);
}

if (res.status === 401) {
// Unauthorized, likely due to expired token
token = await refreshToken();
const response = await fetch(`${API_URL}/v1/${url}`, options);

res = await fetch(`${API_URL}/v1/${url}`, {
method,
headers: {
"Content-Type": "application/json",
"Accepts-Version": "v1",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
if (response.status === 401) {
throw new Error("Unauthorized");
}
throw new Error(`HTTP error! status: ${response.status}`);
}

return await handleApiResponse(res);
return handleApiResponse(response);
};

try {
let token = await getAuthToken();

try {
return await makeRequest(token);
} catch (error) {
if (error instanceof Error && error.message === "Unauthorized") {
MocksiRollbar.log("Received 401 from API, refreshing token");
token = await refreshToken();
return await makeRequest(token);
}
throw error;
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
MocksiRollbar.error("API call failed: ", errorMessage);
throw new Error(`API call failed: ${errorMessage}`);
}
};
12 changes: 12 additions & 0 deletions apps/mocksi-lite/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,18 @@ export const getEmail = async (): Promise<string | null> => {
const storedData = value[STORAGE_KEY] || "{}";
try {
const parsedData = JSON.parse(storedData);
if (!parsedData.email) {
const configPayload = {
payload: {
person: {
id: parsedData.userId,
email: parsedData.email,
},
},
};
console.log("configuring rollbar with user data", parsedData);
MocksiRollbar.configure(configPayload);
}
return parsedData.email;
} catch (error) {
console.log("Error parsing data from storage: ", error);
Expand Down

0 comments on commit 6f13196

Please sign in to comment.