2024-11-14 03:51:08 +00:00
|
|
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
|
|
import type { Request, Response } from "express";
|
|
|
|
import { updates } from "../db/schema.js";
|
|
|
|
import { desc, eq } from "drizzle-orm";
|
|
|
|
import fs from "node:fs/promises";
|
|
|
|
|
2024-11-17 19:16:27 +00:00
|
|
|
const nonceChars =
|
|
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_";
|
|
|
|
let nonce: string;
|
|
|
|
export function setNonce() {
|
|
|
|
nonce = "";
|
|
|
|
for (let i = 0; i < 32; i++)
|
|
|
|
nonce += nonceChars[Math.floor(Math.random() * nonceChars.length)];
|
|
|
|
return nonce;
|
|
|
|
}
|
|
|
|
export function getNonce() {
|
|
|
|
if (!nonce)
|
|
|
|
throw new Error("Nonce doesn't exist");
|
|
|
|
return nonce;
|
|
|
|
}
|
|
|
|
|
2024-11-14 03:51:08 +00:00
|
|
|
let moods: string[], moodsSorted: string[];
|
|
|
|
export async function getMoods() {
|
|
|
|
if (!moods)
|
|
|
|
moods = (await fs.readFile("./static/moods.txt"))
|
|
|
|
.toString("utf-8")
|
|
|
|
.split(";");
|
|
|
|
if (!moodsSorted) moodsSorted = Array.from(moods).sort();
|
|
|
|
return { moods, moodsSorted };
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function render(
|
|
|
|
db: NodePgDatabase,
|
|
|
|
page: string,
|
|
|
|
title: string,
|
|
|
|
res: Response,
|
|
|
|
req: Request,
|
|
|
|
stuff?: Object
|
|
|
|
) {
|
|
|
|
//? maybe you should cache this and save the current mood to the session until it's changed
|
|
|
|
const { moods } = await getMoods();
|
|
|
|
let currentMood: string;
|
|
|
|
if (req.session["loggedIn"]) {
|
|
|
|
const update = (
|
|
|
|
await db
|
|
|
|
.select({ mood: updates.mood })
|
|
|
|
.from(updates)
|
|
|
|
.where(eq(updates.user, req.session["uid"]))
|
|
|
|
.orderBy(desc(updates.date))
|
|
|
|
.limit(1)
|
|
|
|
)[0];
|
|
|
|
currentMood = moods[update?.mood];
|
|
|
|
}
|
|
|
|
|
|
|
|
const o = {
|
|
|
|
title,
|
|
|
|
session: req.session,
|
|
|
|
flashes: req.flash(),
|
|
|
|
moods,
|
2024-11-17 19:16:27 +00:00
|
|
|
currentMood,
|
|
|
|
nonce
|
2024-11-14 03:51:08 +00:00
|
|
|
};
|
|
|
|
res.render(page, { ...o, ...stuff });
|
|
|
|
}
|