Fixed visibility toggle bugs

This commit is contained in:
Atridad Lahiji 2023-10-22 22:56:45 -06:00
parent 4aacaae1ec
commit c2176ca0ee
No known key found for this signature in database
3 changed files with 89 additions and 68 deletions

View file

@ -39,10 +39,7 @@ const VoteUI = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { const { data: roomFromDb, isLoading: roomFromDbLoading } = useQuery({
data: roomFromDb,
isLoading: roomFromDbLoading,
} = useQuery({
queryKey: ["room"], queryKey: ["room"],
queryFn: getRoomHandler, queryFn: getRoomHandler,
retry: false, retry: false,
@ -83,7 +80,7 @@ const VoteUI = () => {
}, },
// If the mutation fails, // If the mutation fails,
// use the context returned from onMutate to roll back // use the context returned from onMutate to roll back
onError: (err, newTodo, context) => { onError: (err, newVote, context) => {
queryClient.setQueryData(["votes"], context?.previousVotes); queryClient.setQueryData(["votes"], context?.previousVotes);
}, },
// Always refetch after error or success: // Always refetch after error or success:
@ -116,9 +113,9 @@ const VoteUI = () => {
id: old?.id, id: old?.id,
userId: old?.userId, userId: old?.userId,
logs: old?.logs, logs: old?.logs,
storyName: storyNameText, storyName: data.reset ? storyNameText : old.storyName,
visible: data.visible, visible: data.visible,
scale: roomScale, scale: data.reset ? roomScale : old.scale,
reset: data.reset, reset: data.reset,
log: data.log, log: data.log,
} }
@ -130,7 +127,7 @@ const VoteUI = () => {
}, },
// If the mutation fails, // If the mutation fails,
// use the context returned from onMutate to roll back // use the context returned from onMutate to roll back
onError: (err, newTodo, context) => { onError: (err, newRoom, context) => {
queryClient.setQueryData(["room"], context?.previousRoom); queryClient.setQueryData(["room"], context?.previousRoom);
}, },
// Always refetch after error or success: // Always refetch after error or success:
@ -176,6 +173,11 @@ const VoteUI = () => {
reset: boolean | undefined; reset: boolean | undefined;
log: boolean | undefined; log: boolean | undefined;
}) { }) {
console.log({
visible: data.visible,
reset: data.reset ? data.reset : false,
log: data.log ? data.log : false,
});
if (roomFromDb) { if (roomFromDb) {
await fetch(`/api/internal/room/${roomId}`, { await fetch(`/api/internal/room/${roomId}`, {
cache: "no-cache", cache: "no-cache",
@ -307,11 +309,8 @@ const VoteUI = () => {
if (roomFromDb) { if (roomFromDb) {
setStoryNameText(roomFromDb.storyName || ""); setStoryNameText(roomFromDb.storyName || "");
setRoomScale(roomFromDb.scale || "ERROR"); setRoomScale(roomFromDb.scale || "ERROR");
} else {
void getRoomHandler();
void getVotesHandler();
} }
}, [roomFromDb, roomId, user]); }, [roomFromDb]);
// UI // UI
// ================================= // =================================

View file

@ -21,3 +21,29 @@ export const publishToChannel = async (
} }
); );
}; };
export const publishToMultipleChannels = async (
channels: string[],
events: EventType[],
message: string
) => {
const response = await fetch(`https://rest.ably.io/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${btoa(env.ABLY_API_KEY)}`,
},
body: JSON.stringify({
channels: channels.map((channel) => `${env.APP_ENV}-${channel}`),
messages: events.map((event) => {
return {
name: event,
data: message,
};
}),
}),
});
const json = await response.json();
console.log(json);
};

View file

@ -1,6 +1,6 @@
import { NextResponse, type NextRequest } from "next/server"; import { NextResponse, type NextRequest } from "next/server";
import { publishToChannel } from "@/_lib/ably"; import { publishToChannel, publishToMultipleChannels } from "@/_lib/ably";
import { db } from "@/_lib/db"; import { db } from "@/_lib/db";
import { invalidateCache } from "@/_lib/redis"; import { invalidateCache } from "@/_lib/redis";
import { logs, rooms, votes } from "@/_lib/schema"; import { logs, rooms, votes } from "@/_lib/schema";
@ -63,23 +63,11 @@ export async function DELETE(
const success = deletedRoom.length > 0; const success = deletedRoom.length > 0;
if (success) { if (success) {
await publishToChannel(
`${userId}`,
EventTypes.ROOM_LIST_UPDATE,
JSON.stringify(deletedRoom)
);
await publishToChannel(
`${params.roomId}`,
EventTypes.ROOM_UPDATE,
JSON.stringify(deletedRoom)
);
await invalidateCache(`kv_roomlist_${userId}`); await invalidateCache(`kv_roomlist_${userId}`);
await publishToChannel( await publishToMultipleChannels(
`${userId}`, [`${userId}`, `${params.roomId}`],
EventTypes.ROOM_LIST_UPDATE, [EventTypes.ROOM_LIST_UPDATE, EventTypes.ROOM_UPDATE],
JSON.stringify(deletedRoom) JSON.stringify(deletedRoom)
); );
@ -119,50 +107,58 @@ export async function PUT(
}); });
} }
if (reqBody.log) {
const oldRoom = await db.query.rooms.findFirst({
where: eq(rooms.id, params.roomId),
with: {
votes: true,
logs: true,
},
});
oldRoom &&
(await db.insert(logs).values({
id: `log_${createId()}`,
created_at: Date.now().toString(),
userId: userId || "",
roomId: params.roomId,
scale: oldRoom.scale,
votes: JSON.stringify(
oldRoom.votes.map((vote) => {
return {
name: vote.userId,
value: vote.value,
};
})
),
roomName: oldRoom.roomName,
storyName: oldRoom.storyName,
}));
}
if (reqBody.reset) { if (reqBody.reset) {
if (reqBody.log) {
const oldRoom = await db.query.rooms.findFirst({
where: eq(rooms.id, params.roomId),
with: {
votes: true,
logs: true,
},
});
oldRoom &&
(await db.insert(logs).values({
id: `log_${createId()}`,
created_at: Date.now().toString(),
userId: userId || "",
roomId: params.roomId,
scale: oldRoom.scale,
votes: JSON.stringify(
oldRoom.votes.map((vote) => {
return {
name: vote.userId,
value: vote.value,
};
})
),
roomName: oldRoom.roomName,
storyName: oldRoom.storyName,
}));
}
await db.delete(votes).where(eq(votes.roomId, params.roomId)); await db.delete(votes).where(eq(votes.roomId, params.roomId));
} }
const newRoom = await db const newRoom = reqBody.reset
.update(rooms) ? await db
.set({ .update(rooms)
storyName: reqBody.name, .set({
visible: reqBody.visible, storyName: reqBody.name,
scale: [...new Set(reqBody.scale.split(","))] visible: reqBody.visible,
.filter((item) => item !== "") scale: [...new Set(reqBody.scale.split(","))]
.toString(), .filter((item) => item !== "")
}) .toString(),
.where(eq(rooms.id, params.roomId)) })
.returning(); .where(eq(rooms.id, params.roomId))
.returning()
: await db
.update(rooms)
.set({
visible: reqBody.visible,
})
.where(eq(rooms.id, params.roomId))
.returning();
const success = newRoom.length > 0; const success = newRoom.length > 0;