Skip to content

Commit

Permalink
Fix checkbox and add logger (#2438)
Browse files Browse the repository at this point in the history
  • Loading branch information
omfj authored Jan 28, 2025
1 parent fcb880e commit dda8274
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 43 deletions.
22 changes: 22 additions & 0 deletions apps/api/src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const APP = "API";

export const Logger = {
info: (message: string, metadata?: Record<string, unknown>) => {
const timestamp = new Date().toISOString();
console.info(
JSON.stringify({ app: APP, ts: timestamp, severity: "INFO", message, ...metadata }),
);
},
error: (message: string, metadata?: Record<string, unknown>) => {
const timestamp = new Date().toISOString();
console.error(
JSON.stringify({ app: APP, ts: timestamp, severity: "ERROR", message, ...metadata }),
);
},
warn: (message: string, metadata?: Record<string, unknown>) => {
const timestamp = new Date().toISOString();
console.warn(
JSON.stringify({ app: APP, ts: timestamp, severity: "WARN", message, ...metadata }),
);
},
};
38 changes: 26 additions & 12 deletions apps/api/src/services/admin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isFuture, isPast } from "date-fns";
import { and, eq, gte, lte, or, sql } from "drizzle-orm";
import { and, eq, or, sql } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";

Expand All @@ -12,11 +12,11 @@ import {
users,
} from "@echo-webkom/db/schemas";

import { Logger } from "@/lib/logger";
import { fitsInSpotrange, isAvailableSpot } from "@/utils/is-available-spot";
import { validateQuestions } from "@/utils/validate-questions";
import { db } from "../lib/db";
import { admin } from "../middleware/admin";
import { findCorrectSpotRange } from "../utils/find-correct-spot-range";
import { parseJson } from "../utils/json";

const app = new Hono();
Expand Down Expand Up @@ -116,13 +116,16 @@ app.post("/admin/register", admin(), async (c) => {
questions: z.array(
z.object({
questionId: z.string(),
answer: z.string(),
answer: z.string().or(z.array(z.string())),
}),
),
}),
);

if (!ok) {
const data = await c.req.json();
Logger.error("Invalid data", data);

return c.json({ error: "Invalid data" }, 400);
}

Expand All @@ -136,9 +139,10 @@ app.post("/admin/register", admin(), async (c) => {
});

if (!user) {
console.error("User not found", {
Logger.warn("User not found", {
userId,
});

return c.json(
{
success: false,
Expand All @@ -149,6 +153,10 @@ app.post("/admin/register", admin(), async (c) => {
}

if (!user.degreeId || !user.year || !user.hasReadTerms) {
Logger.warn("User has not filled out study information", {
userId,
});

return c.json(
{
success: false,
Expand All @@ -166,9 +174,10 @@ app.post("/admin/register", admin(), async (c) => {
});

if (!happening) {
console.error("Happening not found", {
Logger.error("Happening not found", {
happeningId,
});

return c.json(
{
success: false,
Expand All @@ -191,7 +200,7 @@ app.post("/admin/register", admin(), async (c) => {
});

if (exisitingRegistration) {
console.error("Registration already exists", {
Logger.warn("Registration already exists", {
userId,
happeningId,
});
Expand All @@ -216,7 +225,7 @@ app.post("/admin/register", admin(), async (c) => {
* Check if registration is open for user that can not early register
*/
if (!canEarlyRegister && happening.registrationStart && isFuture(happening.registrationStart)) {
console.error("Registration is not open", {
Logger.warn("Registration is not open", {
userId: userId,
happeningId,
});
Expand All @@ -230,7 +239,7 @@ app.post("/admin/register", admin(), async (c) => {
}

if (!canEarlyRegister && !happening.registrationStart) {
console.error("Registration is not open", {
Logger.warn("Registration is not open", {
userId,
happeningId,
});
Expand All @@ -247,7 +256,7 @@ app.post("/admin/register", admin(), async (c) => {
* Check if registration is closed for user that can not early register
*/
if (happening.registrationEnd && isPast(happening.registrationEnd)) {
console.error("Registration is closed", {
Logger.warn("Registration is closed", {
userId,
happeningId,
});
Expand Down Expand Up @@ -289,7 +298,7 @@ app.post("/admin/register", admin(), async (c) => {
spotRanges.some((spotRange) => fitsInSpotrange(user, spotRange)) || canSkipSpotRange;

if (!userIsEligible) {
console.error("User is not in any spot range", {
Logger.warn("User is not in any spot range", {
userId,
happeningId,
});
Expand All @@ -308,7 +317,7 @@ app.post("/admin/register", admin(), async (c) => {
const allQuestionsAnswered = validateQuestions(happening.questions, questions);

if (!allQuestionsAnswered) {
console.error("Not all questions are answered", {
Logger.warn("Not all questions are answered", {
userId,
happeningId,
});
Expand Down Expand Up @@ -366,6 +375,11 @@ app.post("/admin/register", admin(), async (c) => {
);

if (!registration) {
Logger.error("Failed to update registration", {
userId,
happeningId,
});

throw new Error("Failed to update registration");
}

Expand All @@ -390,7 +404,7 @@ app.post("/admin/register", admin(), async (c) => {
await db.insert(answers).values(answersToInsert).onConflictDoNothing();
}

console.info("Successful registration", {
Logger.info("Successfully registered user", {
userId: user.id,
happeningId: happening.id,
isWaitlisted,
Expand Down
37 changes: 19 additions & 18 deletions apps/web/src/actions/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,24 @@ export const register = async (id: string, payload: z.infer<typeof registrationF
const userId = user.id;
const questions = payload.questions;

const resp = await apiServer
.post("admin/register", {
json: {
happeningId,
userId,
questions,
},
})
.json<{ success: boolean; message: string }>()
.catch((err) => {
console.error("FATAL. Failed to connect to API", err);

return {
success: false,
message: "Fikk ikke koblet til API.",
};
});
try {
const resp = await apiServer
.post("admin/register", {
json: {
happeningId,
userId,
questions,
},
})
.json<{ success: boolean; message: string }>();

return resp;
} catch (error) {
console.error("Failed to register");

return resp;
return {
success: false,
message: "Noe gikk galt på serveren. Kontakt en i Webkom.",
};
}
};
9 changes: 6 additions & 3 deletions apps/web/src/app/(default)/arrangement/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ const getData = cache(async (slug: string) => {
return repeatingEvent;
}

console.info("Event not found", {
slug,
});
console.info(
JSON.stringify({
message: "Event not found",
slug,
}),
);

return notFound();
});
Expand Down
9 changes: 6 additions & 3 deletions apps/web/src/app/(default)/bedpres/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ const getData = cache(async (slug: string) => {
const event = await fetchHappeningBySlug(slug);

if (!event) {
console.info("Bedpres not found", {
slug,
});
console.info(
JSON.stringify({
message: "Bedpres not found",
slug,
}),
);
return notFound();
}

Expand Down
4 changes: 1 addition & 3 deletions apps/web/src/app/api/sanity/revalidate/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ export const POST = withBasicAuth(async (req) => {
slug: string | null;
};

console.info("Revalidating static content", {
type,
});
console.info(`Revalidating static content for ${type}`);

// await fetch("https://beta.echo-webkom.no/api/sanity/revalidate", {
// method: "POST",
Expand Down
11 changes: 7 additions & 4 deletions apps/web/src/auth/auth-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,13 @@ export const authOptions: AuthOptions = {
return true;
}

console.info("Sign in failed", {
email,
error,
});
console.info(
JSON.stringify({
message: "Failed login attempt",
email,
error,
}),
);

const id = nanoid();
await signInAttempt.set(
Expand Down

0 comments on commit dda8274

Please sign in to comment.