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-01 14:57:31 -07:00
|
|
|
import { fetchCache, setCache } from "~/services/redis.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 });
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
return json("Not Signed In!", {
|
|
|
|
status: 403,
|
|
|
|
statusText: "UNAUTHORIZED!",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return eventStream(request.signal, function setup(send) {
|
|
|
|
async function handler() {
|
2023-12-01 14:57:31 -07:00
|
|
|
fetchCache<
|
|
|
|
{
|
|
|
|
id: string;
|
|
|
|
createdAt: Date;
|
|
|
|
roomName: string;
|
|
|
|
}[]
|
2023-12-01 16:15:21 -07:00
|
|
|
>(`kv_roomlist_${userId}`, "sp").then((cachedResult) => {
|
2023-12-01 14:57:31 -07:00
|
|
|
if (cachedResult) {
|
|
|
|
send({ event: userId!, data: JSON.stringify(cachedResult) });
|
|
|
|
} else {
|
|
|
|
db.query.rooms
|
|
|
|
.findMany({
|
|
|
|
where: eq(rooms.userId, userId || ""),
|
|
|
|
})
|
|
|
|
.then((roomList) => {
|
2023-12-14 17:11:07 -07:00
|
|
|
Promise.all([
|
|
|
|
setCache(`kv_roomlist_${userId}`, roomList, "sp"),
|
|
|
|
send({ event: userId!, data: JSON.stringify(roomList) }),
|
|
|
|
]);
|
2023-12-01 14:57:31 -07:00
|
|
|
});
|
|
|
|
}
|
2023-04-20 04:20:00 -06:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initial fetch
|
2023-12-01 14:57:31 -07:00
|
|
|
fetchCache<
|
|
|
|
{
|
|
|
|
id: string;
|
|
|
|
createdAt: Date;
|
|
|
|
roomName: string;
|
|
|
|
}[]
|
2023-12-01 16:15:21 -07:00
|
|
|
>(`kv_roomlist_${userId}`, "sp").then((cachedResult) => {
|
2023-12-01 14:57:31 -07:00
|
|
|
if (cachedResult) {
|
|
|
|
send({ event: userId!, data: JSON.stringify(cachedResult) });
|
|
|
|
} else {
|
|
|
|
db.query.rooms
|
|
|
|
.findMany({
|
|
|
|
where: eq(rooms.userId, userId || ""),
|
|
|
|
})
|
|
|
|
.then((roomList) => {
|
2023-12-14 17:11:07 -07:00
|
|
|
Promise.all([
|
|
|
|
setCache(`kv_roomlist_${userId}`, roomList, "sp"),
|
|
|
|
send({ event: userId!, data: JSON.stringify(roomList) }),
|
|
|
|
]);
|
2023-12-01 14:57:31 -07:00
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
2023-04-20 04:20:00 -06:00
|
|
|
|
|
|
|
emitter.on("roomlist", handler);
|
|
|
|
|
|
|
|
return function clear() {
|
|
|
|
emitter.off("roomlist", handler);
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|