Skip to content

Commit

Permalink
Merge pull request #789 from isucon/cherry-pick-fe
Browse files Browse the repository at this point in the history
[fe] cherry-pick
  • Loading branch information
imamiya-masaki authored Dec 7, 2024
2 parents 725797f + 63119e3 commit d089671
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions frontend/app/components/hooks/use-emulator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useEffect } from "react";
import { apiBaseURL } from "~/api/api-base-url";
import {
ChairGetNotificationResponse,
fetchChairPostCoordinate,
fetchChairPostRideStatus,
} from "~/api/api-components";
Expand Down Expand Up @@ -37,14 +39,53 @@ const move = (
}
};

function jsonFromSseResult<T>(value: string) {
const data = value.slice("data:".length).trim();
return JSON.parse(data) as T;
}

const notificationFetch = async () => {
try {
const notification = await fetch(`${apiBaseURL}/chair/notification`);
const isEventStream = !!notification?.headers
.get("Content-type")
?.split(";")?.[0]
.includes("text/event-stream");

if (isEventStream) {
const reader = notification.body?.getReader();
const decoder = new TextDecoder();
const readed = (await reader?.read())?.value;
const decoded = decoder.decode(readed);
const json =
jsonFromSseResult<ChairGetNotificationResponse["data"]>(decoded);
return { data: json };
}
const json = (await notification.json()) as
| ChairGetNotificationResponse
| undefined;
return json;
} catch (error) {
console.error(error);
}
};

const getStatus = async () => {
const notification = await notificationFetch();
return notification?.data?.status;
};

const currentCoodinatePost = (coordinate: Coordinate) => {
setSimulatorCurrentCoordinate(coordinate);
return fetchChairPostCoordinate({
body: coordinate,
});
};

const postEnroute = (rideId: string, coordinate: Coordinate) => {
const postEnroute = async (rideId: string, coordinate: Coordinate) => {
if ((await getStatus()) !== "MATCHING") {
return;
}
setSimulatorStartCoordinate(coordinate);
return fetchChairPostRideStatus({
body: { status: "ENROUTE" },
Expand All @@ -54,7 +95,10 @@ const postEnroute = (rideId: string, coordinate: Coordinate) => {
});
};

const postCarring = (rideId: string) => {
const postCarring = async (rideId: string) => {
if ((await getStatus()) !== "PICKUP") {
return;
}
return fetchChairPostRideStatus({
body: { status: "CARRYING" },
pathParams: {
Expand Down

0 comments on commit d089671

Please sign in to comment.