Skip to content

Commit

Permalink
debug: why it does not run on server, why GET and not POST
Browse files Browse the repository at this point in the history
  • Loading branch information
mgierada committed Jun 21, 2024
1 parent 0ea6461 commit 0d44e7b
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 86 deletions.
6 changes: 4 additions & 2 deletions server/handlers/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,16 @@ func recordEvent(w http.ResponseWriter, r *http.Request, tableToResetAndLock str
}

func RecordOhNoEvent(w http.ResponseWriter, r *http.Request) {
log.Printf("🔗 received /ohno request")
log.Printf("🔗 received /ohno request of type %s", r.Method)
serverResponseOkMessage := "Oh No! Event recorded"
utils.EnableCors(&w, r)
recordEvent(w, r, utils.TableInstance.Counter, utils.TableInstance.OhnoCounter, utils.TableInstance.HistoricalCounter, serverResponseOkMessage)

}

func RecordFineEvent(w http.ResponseWriter, r *http.Request) {
log.Printf("🔗 received /fine request")
log.Printf("🔗 received /fine request of type %s", r.Method)
serverResponseOkMessage := "It's all good now! Event recorded"
utils.EnableCors(&w, r)
recordEvent(w, r, utils.TableInstance.OhnoCounter, utils.TableInstance.Counter, utils.TableInstance.HistoricalOhnoCounter, serverResponseOkMessage)
}
80 changes: 6 additions & 74 deletions ui/src/app/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,65 +3,7 @@ import Callendar from "@/components/Callendar";
import { DisplayCard } from "@/components/Card";
import HealthStatus from "@/components/HealthStatus";
import { ActionButton } from "@/components/ActionButton";

/**
* @typedef {Object} CounterApiResponse
* @property {number} CurrentValue - The current value of the counter.
* @property {number} MaxValue - the maximum value of the counter recorded so far.
* @property {string} UpdatedAt - The timestamp when the counter was last updated.
* @property {Object} ResetedAt - The reset information.
* @property {string} ResetedAt.String - The timestamps when the counter was reset.
* @property {boolean} ResetedAt.Valid - The validity of the reset object timestamps.
* @property {boolean} IsLocked - Indicates if the counter is locked.
*/

/**
* @typedef {Object} Counter
* @property {number|null} currentValue - The current value of the counter.
* @property {number|null} maxValue - The max value of the counter recorded so far.
* @property {string|null} updatedAt - The timestamps when the last update was made.
* @property {boolean} isLocked - A flag indicating whether the counter updates are currently locked
* @property {string|null} resetedAt - The timestamps when the counter was reset.
* @property {boolean|null} wasEverReset - The validity of the reset object timestamps.
* @property {string|null} error - The error message if fetching failed.
*/

/**
* @typedef {Object } RecordEventApiResponse
* @property {string} message - The message returned from the API.
*/

/**
* Records an event to the API.
* @param {string} endpoint - The endpoint to record the event to.
* @returns {Promise<void>} A promise that resolves when the event is successfully recorded.
*/
const recordEvent = async (endpoint) => {
try {
const rootUrl = process.env.NEXT_PUBLIC_ROOT_API_URL;
const url = `${rootUrl}/${endpoint}`;

const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});

if (!response.ok) {
throw new Error("Failed to record event");
}

/** @type {RecordEventApiResponse} */
const data = await response.json();
if (!data || !data.message) {
throw new Error("Invalid response data");
}
return;
} catch (error) {
throw new Error(`Error recording event: ${error}`);
}
};
import { recordEvent } from "@/utils/actions";

/**
* Fetches the current value of the counter from the API.
Expand All @@ -79,14 +21,12 @@ const fetchCounter = async (endpoint) => {
throw new Error("Failed to fetch data");
}

/** @type {CounterApiResponse} */
const data = await response.json();

if (!data) {
throw new Error("Invalid response data");
}

/** @type {Counter} */
const result = {
currentValue: data.CurrentValue,
maxValue: data.MaxValue,
Expand All @@ -98,7 +38,6 @@ const fetchCounter = async (endpoint) => {
};
return result;
} catch (error) {
/** @type {Counter} */
return {
currentValue: null,
maxValue: null,
Expand All @@ -116,17 +55,9 @@ const fetchCounter = async (endpoint) => {
* @returns {JSX.Element} The Home component.
*/
const Home = async () => {
/** @type {Counter} */
const dataHealthyCounter = await fetchCounter("counter");
/**@type {Counter} */
const dataIllnessCounter = await fetchCounter("ohno-counter");

/**
* Method to render the counter display conditionally
* @param {Counter} dataHealthyCounter - The healthy counter data.
* @param {Counter} dataIllnessCounter - The illness counter data.
* @returns {JSX.Element} The counter display component
*/
const renderCounterDisplay = (dataHealthyCounter, dataIllnessCounter) => {
if (dataHealthyCounter.error && dataIllnessCounter.error) {
return (
Expand Down Expand Up @@ -189,10 +120,6 @@ const Home = async () => {
error={dataHealthyCounter.error}
/>
{renderCounterDisplay(dataHealthyCounter, dataIllnessCounter)}
{/* <CounterDisplay */}
{/* currentValue={dataHealthyCounter.currentValue} */}
{/* error={dataHealthyCounter.error} */}
{/* /> */}
<Callendar
className="mt-5"
lastTimeReseted={dataHealthyCounter.resetedAt}
Expand All @@ -211,6 +138,10 @@ const Home = async () => {
alertDialogDescription={`
This action cannot be undone.
This will reset the healthy counter and start the sick interval.`}
handleUpdate={async function s() {
"use server";
return recordEvent("ohno");
}}
/>
<ActionButton
variant="outline"
Expand All @@ -220,6 +151,7 @@ const Home = async () => {
alertDialogDescription={`
This action cannot be undone.
This will reset the sick counter and start the healthy interval.`}
// handleUpdate={recordEvent("fine")}
/>
</div>
</main>
Expand Down
32 changes: 22 additions & 10 deletions ui/src/components/ActionButton/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
* @property {string} ctaButton - the call to action to be displayed on the button
* @property {string} icon - the icon to be displayed on the button
* @property {string} alertDialogDescription - description text shown on the alert dialog
* @property {function} handleUpdate - function to be called when the button is clicked
*/

/**
Expand All @@ -36,6 +37,7 @@ export function ActionButton({
ctaButton,
icon,
alertDialogDescription,
handleUpdate,
}) {
const [showAlertDialog, setShowAlertDialog] = useState(false);

Expand All @@ -48,16 +50,26 @@ export function ActionButton({
return null;
};

const handleConfirm = () => {
toast(toastMessage, {
description: getAndFormatCurrentDate(),
action: {
label: "Dismiss",
},
});
//TODO: add integration with backed
console.log("Event has been recorded");
setShowAlertDialog(false);
const handleConfirm = async () => {
try {
await handleUpdate();
toast(toastMessage, {
description: getAndFormatCurrentDate(),
action: {
label: "Dismiss",
},
});
console.log("Event has been recorded");
setShowAlertDialog(false);
} catch (error) {
console.error("Failed to record an event:", error);
toast("Failed to record an event", {
description: error.message,
action: {
label: "Dismiss",
},
});
}
};

return (
Expand Down
41 changes: 41 additions & 0 deletions ui/src/utils/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"use server";

/**
* @typedef {Object } RecordEventApiResponse
* @property {string} message - The message returned from the API.
*/

/**
* Records an event to the API.
* @param {string} endpoint - The endpoint to record the event to.
* @returns {Promise<void>} A promise that resolves when the event is successfully recorded.
*/
export const recordEvent = async (endpoint) => {
// "use server";
try {
const rootUrl = process.env.NEXT_PUBLIC_ROOT_API_URL;
const url = `${rootUrl}/${endpoint}`;

const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});

console.log("response: ", response);

if (!response.ok) {
throw new Error("Failed to record event");
}

const data = await response.json();
if (!data || !data.message) {
throw new Error("Invalid response data");
}
return;
} catch (error) {
console.log(error);
throw new Error(`Error recording event: ${error.message}`);
}
};

0 comments on commit 0d44e7b

Please sign in to comment.