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

Commit

Permalink
fetch initial recordings and render app using initial state (#98)
Browse files Browse the repository at this point in the history
* recordings fetch initial

* formatting

* use initial recordings

* fixed response body usage

* formatting
  • Loading branch information
bkd705 authored Jul 18, 2024
1 parent 515f902 commit 6b0c2cc
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 56 deletions.
42 changes: 32 additions & 10 deletions apps/mocksi-lite/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,28 +301,36 @@ async function deleteDemo(data: Record<string, unknown>) {
apiCall(`recordings/${id}`, "DELETE").then(() => getRecordings());
}

async function getRecordings() {
async function getRecordings(): Promise<Recording[]> {
const email = await getEmail();

if (email) {
if (!email) {
console.error("Email not found. Cannot fetch recordings.");
return [];
}

try {
const response = await apiCall(
`recordings?creator=${encodeURIComponent(email)}`,
).catch((err) => {
console.error(`Failed to fetch recordings: ${err}`);
return null;
});
);

if (!response || response.length === 0) {
console.error("No recordings found or failed to fetch recordings.");
chrome.storage.local.set({ recordings: "[]" });
return;
return [];
}

const sorted = response.sort((a: Recording, b: Recording) =>
a.updated_timestamp > b.updated_timestamp ? -1 : 0,
);

const recordings = JSON.stringify(sorted) || "[]";
chrome.storage.local.set({ recordings });
} else {
console.error("Email not found. Cannot fetch recordings.");

return sorted;
} catch (err) {
console.error(`Failed to fetch recordings: ${err}`);
return [];
}
}

Expand Down Expand Up @@ -506,7 +514,21 @@ chrome.runtime.onMessage.addListener(
}

if (request.message === "getRecordings") {
getRecordings();
getRecordings()
.then((recordings) => {
sendResponse({
message: "getRecordings",
status: "success",
body: { recordings },
});
})
.catch((err) => {
sendResponse({
message: "getRecordings",
status: "error",
body: { err },
});
});
return true;
}

Expand Down
74 changes: 33 additions & 41 deletions apps/mocksi-lite/content/AppStateContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,52 +106,44 @@ const localStorageMiddleware = (reducer: typeof appStateReducer) => {
};
};

export const AppStateProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
export const AppStateProvider: React.FC<{
children: React.ReactNode;
initialRecordings?: Recording[];
}> = ({ children, initialRecordings }) => {
const reducer = localStorageMiddleware(appStateReducer);
const [state, dispatch] = useReducer(reducer, INITIAL_STATE);

// Load the initial state from chrome storage on mount
useEffect(() => {
chrome.storage.local.get(
[MOCKSI_RECORDING_STATE, "recordings"],
(result) => {
if (result[MOCKSI_RECORDING_STATE] === AppState.UNAUTHORIZED) {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: AppState.UNAUTHORIZED,
});
return;
}

let recordings = [];

if (result.recordings) {
try {
recordings = JSON.parse(result.recordings);
} catch (e) {
console.error(e);
}
}

if (
recordings?.length &&
recordings.some((rec: Recording) => rec.url === window.location.href)
) {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: result[MOCKSI_RECORDING_STATE],
});
} else {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: AppState.READYTORECORD,
});
}
},
);
}, []);
chrome.storage.local.get([MOCKSI_RECORDING_STATE], (result) => {
if (result[MOCKSI_RECORDING_STATE] === AppState.UNAUTHORIZED) {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: AppState.UNAUTHORIZED,
});
return;
}

console.log({ initialRecordings });

if (
initialRecordings?.length &&
initialRecordings.some(
(rec: Recording) => rec.url === window.location.href,
)
) {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: result[MOCKSI_RECORDING_STATE],
});
} else {
dispatch({
event: AppEvent.SET_INITIAL_STATE,
payload: AppState.READYTORECORD,
});
}
});
}, [initialRecordings]);

const value = {
state,
Expand Down
12 changes: 10 additions & 2 deletions apps/mocksi-lite/content/ContentApp.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useContext, useEffect, useState } from "react";
import useShadow from "use-shadow-dom";
import type { Recording } from "../background";
import { MOCKSI_LAST_PAGE_DOM } from "../consts";
import { innerHTMLToJson, logout, setRootPosition } from "../utils";
import {
Expand All @@ -23,6 +24,9 @@ import("./base.css");
interface ContentProps {
isOpen?: boolean;
email?: string;
initialState?: {
recordings?: Recording[];
};
}

function ShadowContentApp({ isOpen, email }: ContentProps) {
Expand Down Expand Up @@ -110,10 +114,14 @@ const extractStyles = (): string => {
return styles;
};

export default function ContentApp({ isOpen, email }: ContentProps) {
export default function ContentApp({
isOpen,
email,
initialState,
}: ContentProps) {
const styles = extractStyles();
return useShadow(
<AppStateProvider>
<AppStateProvider initialRecordings={initialState?.recordings}>
<ShadowContentApp isOpen={isOpen} email={email} />
</AppStateProvider>,
[],
Expand Down
18 changes: 15 additions & 3 deletions apps/mocksi-lite/content/content.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ReactDOM from "react-dom/client";
import type { Recording } from "../background";
import {
MOCKSI_AUTH,
MOCKSI_RECORDING_STATE,
Expand Down Expand Up @@ -80,9 +81,20 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {

setRootPosition(state);

sendMessage("getRecordings");

root.render(<ContentApp isOpen={true} email={email || ""} />);
sendMessage("getRecordings", {}, (response) => {
const { body } = response;
const { recordings } = body as { recordings: Recording[] };

root.render(
<ContentApp
isOpen={true}
email={email || ""}
initialState={{
recordings,
}}
/>,
);
});
});
});
}
Expand Down
3 changes: 3 additions & 0 deletions apps/mocksi-lite/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ const getHTMLElementFromSelector = (
export const sendMessage = (
message: string,
body?: Record<string, unknown> | null,
callback: (response: Record<string, unknown>) => void = () => {},
) => {
try {
chrome.runtime.sendMessage({ message, body }, (response) => {
Expand All @@ -220,6 +221,8 @@ export const sendMessage = (
`Failed to send message to background script. Received response: ${response}`,
);
}

callback(response);
});
} catch (error) {
console.error("Error sending message to background script:", error);
Expand Down

0 comments on commit 6b0c2cc

Please sign in to comment.