pollo/app/routes/api.room.get.$roomId.tsx

79 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-04-20 04:20:00 -06:00
import { getAuth } from "@clerk/remix/ssr.server";
2023-12-13 14:52:56 -07:00
import { type LoaderFunctionArgs, json } from "@remix-run/node";
2023-04-20 04:20:00 -06:00
import { eq } from "drizzle-orm";
import { eventStream } from "remix-utils/sse/server";
import { db } from "~/services/db.server";
import { emitter } from "~/services/emitter.server";
2023-12-11 22:58:49 -07:00
import { rooms } from "~/services/schema.server";
2023-04-20 04:20:00 -06:00
// Get Room List
export async function loader({ context, params, request }: LoaderFunctionArgs) {
const { userId } = await getAuth({ context, params, request });
const roomId = params.roomId;
if (!roomId) {
return json("RoomId Missing!", {
status: 400,
2023-11-27 15:17:27 -07:00
statusText: "The RoomId is Missing!",
2023-04-20 04:20:00 -06:00
});
}
if (!userId) {
return json("Not Signed In!", {
status: 403,
statusText: "UNAUTHORIZED!",
});
}
2023-11-22 16:00:27 -07:00
const room = await db.query.rooms.findFirst({
where: eq(rooms.id, roomId),
});
if (!room) {
2023-11-27 15:17:27 -07:00
throw new Response(null, {
2023-11-22 16:00:27 -07:00
status: 404,
2023-11-27 15:17:27 -07:00
statusText: "NOT NOOOOOO!",
2023-11-22 16:00:27 -07:00
});
}
2023-04-20 04:20:00 -06:00
return eventStream(request.signal, function setup(send) {
async function handler() {
2023-12-01 14:57:31 -07:00
db.query.rooms
.findFirst({
where: eq(rooms.id, roomId || ""),
with: {
logs: true,
},
})
.then((roomFromDb) => {
return send({
event: `room-${roomId}`,
data: JSON.stringify(roomFromDb),
});
});
2023-04-20 04:20:00 -06:00
}
// Initial fetch
db.query.rooms
.findFirst({
where: eq(rooms.id, roomId || ""),
with: {
logs: true,
},
})
.then((roomFromDb) => {
return send({
event: `room-${roomId}`,
data: JSON.stringify(roomFromDb),
});
});
emitter.on("room", handler);
return function clear() {
emitter.off("room", handler);
};
});
}