Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- CreateTable
CREATE TABLE "Note" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
"topicId" TEXT NOT NULL,
"courseId" TEXT NOT NULL,

CONSTRAINT "Note_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Note" ADD CONSTRAINT "Note_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Note" ADD CONSTRAINT "Note_topicId_fkey" FOREIGN KEY ("topicId") REFERENCES "Topic"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Note" ADD CONSTRAINT "Note_courseId_fkey" FOREIGN KEY ("courseId") REFERENCES "Course"("id") ON DELETE CASCADE ON UPDATE CASCADE;
20 changes: 20 additions & 0 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ model Course {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
topics Topic[]
notes Note[]
}

model Topic {
Expand All @@ -66,6 +67,24 @@ model Topic {
userCompletions UserCompletion[]
questions Question[]
userPerformances UserTopicPerformance[]
notes Note[]
}

model Note {
id String @id @default(cuid())
title String
content String @db.Text

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

// --- Relations ---
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
topicId String
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
courseId String
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
}

model UserCompletion {
Expand Down Expand Up @@ -158,6 +177,7 @@ model User {
trackId String?
joinedTrack Track? @relation(fields: [trackId], references: [id], onDelete: Cascade, name: "joinedTrack")
userCompletions UserCompletion[]
notes Note[]

// Instructors
createdTracks Track[]
Expand Down
4 changes: 3 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import express from "express";
import { auth } from "./lib/auth.js";
import { toNodeHandler } from "better-auth/node";
import { admin, adminRouter } from "./lib/admin.js";
import { notesRouter } from "./routes/notes.js";

const app = express();

app.disable("x-powered-by");

app.all("/api/auth/*", toNodeHandler(auth));
app.use(admin.options.rootPath, adminRouter);
console.log(`AdminJS is running under ${admin.options.rootPath}`);
app.use(express.json());
app.use(notesRouter);

export default app;
12 changes: 12 additions & 0 deletions apps/api/src/errors/not-found.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import BaseError from "./base.js";

export class NotFoundError extends BaseError<undefined> {
constructor(hint?: string) {
super(
"Not Found: Ensure the requested resource exists.",
404,
undefined,
hint,
);
}
}
95 changes: 95 additions & 0 deletions apps/api/src/routes/notes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { Router } from "express";
import { validate } from "../middlewares/validate.js";
import {
createNote,
deleteNote,
getAllFilteredNotes,
getNoteById,
updateNote,
} from "../services/notes.js";
import {
CreateNoteBodySchema,
GetAllNotesQuerySchema,
noteIdSchema,
topicIdSchema,
UpdateNoteBodySchema,
} from "../schemas/notes.js";
import { requireAuth } from "../middlewares/auth.js";

const router = Router();

router.use(requireAuth);

router.get(
"/api/notes/:noteId",
validate({ params: noteIdSchema }),
async (req, res) => {
const { noteId } = req.params;
const response = await getNoteById(noteId, req.user!.id);
res.status(200).json({
status: "success",
data: response,
});
},
);

router.get(
"/api/notes",
validate({ query: GetAllNotesQuerySchema }),
async (req, res) => {
const response = await getAllFilteredNotes(req.user!.id, req.query);
res.status(200).json({
status: "success",
pagination: response.pagination,
data: response.data,
});
},
);

router.post(
"/api/topics/:topicId/notes",
validate({ params: topicIdSchema, body: CreateNoteBodySchema }),
async (req, res) => {
const { topicId } = req.params;
const { title, content } = req.body;
const response = await createNote(
{ title, content },
topicId,
req.user!.id,
);
res.status(201).json({
status: "success",
data: response,
});
},
);

router.put(
"/api/notes/:noteId",
validate({ params: noteIdSchema, body: UpdateNoteBodySchema }),
async (req, res) => {
const { noteId } = req.params;
const { title, content } = req.body;

const response = await updateNote(noteId, req.user!.id, { title, content });
res.status(200).json({
status: "success",
data: response,
});
},
);

router.delete(
"/api/notes/:noteId",
validate({ params: noteIdSchema }),
async (req, res) => {
const { noteId } = req.params;
await deleteNote(noteId, req.user!.id);
res.status(204).json({
status: "success",
message: "Note deleted successfully.",
});
},
);

export { router as notesRouter };
92 changes: 92 additions & 0 deletions apps/api/src/schemas/notes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import z from "zod";

export const CreateNoteBodySchema = z.object({
title: z
.string()
.trim()
.min(1, { message: "Title is required and must be at least 1 character." }),
content: z.string().trim().min(1, {
message: "Content is required and must be at least 1 character.",
}),
});

export const NoteSchema = z.object({
id: z.string().cuid({ message: "id must be a valid CUID." }),
title: z.string().min(1, { message: "Title must be at least 1 character." }),
content: z
.string()
.min(1, { message: "Content must be at least 1 character." }),
topicId: z.string().cuid({ message: "topicId must be a valid CUID." }),
userId: z.string().cuid({ message: "userId must be a valid CUID." }),
courseId: z.string().cuid({ message: "courseId must be a valid CUID." }),
createdAt: z.date({ message: "createdAt must be a valid date." }),
updatedAt: z.date({ message: "updatedAt must be a valid date." }),
});

export const UpdateNoteBodySchema = z.object({
title: z
.string()
.trim()
.min(1, { message: "Title must be at least 1 character." })
.optional(),
content: z
.string()
.trim()
.min(1, { message: "Content must be at least 1 character." })
.optional(),
});

// valitate query string
const validSortFields = new Set([
"title",
"-title",
"createdAt",
"-createdAt",
"updatedAt",
"-updatedAt",
]);

export const GetAllNotesQuerySchema = z.object({
courseId: z
.string()
.cuid({ message: "courseId must be a valid CUID." })
.optional(),
topicId: z
.string()
.cuid({ message: "topicId must be a valid CUID." })
.optional(),
search: z.string().optional(),
sort: z
.string()
.refine(
(value) => {
// Ensure every comma-separated value is in whitelist
return value.split(",").every((field) => validSortFields.has(field));
},
{ message: `Invalid sort field.` },
)
.optional(),
page: z.coerce
.number({ message: "page must be an number." })
.int({ message: "page must be an integer." })
.min(1, { message: "page must be at least 1." })
.default(1),
limit: z.coerce
.number({ message: "limit must be an number." })
.int({ message: "limit must be an integer." })
.min(1, { message: "limit must be at least 1." })
.default(10),
});

// valitate params
export const topicIdSchema = z.object({
topicId: z.string().trim().cuid({ message: "id must be a valid CUID." }),
});
export const noteIdSchema = z.object({
noteId: z.string().trim().cuid({ message: "id must be a valid CUID." }),
});

export type NoteServiceType = z.infer<typeof NoteSchema>;
export type UpdateNoteServiceType = z.infer<typeof UpdateNoteBodySchema>;
export type CreateNoteBodyType = z.infer<typeof CreateNoteBodySchema>;
export type GetAllNotesQueryType = z.infer<typeof GetAllNotesQuerySchema>;
Loading
Loading