Skip to content

Commit

Permalink
refactor(controllers/subject.controller, services/subject.service): e…
Browse files Browse the repository at this point in the history
…xtracting the logic onto service layer
  • Loading branch information
elskow committed Nov 14, 2024
1 parent 4eaf715 commit a65ec88
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
24 changes: 10 additions & 14 deletions src/controllers/subject.controller.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import { firestore } from "@/config";
import { Controller, Subject } from "@/types";
import { Container } from "typedi";
import { SubjectService } from "@services/subject.service";
import { Controller } from "@/types";
import { logger } from "@middleware/logging.middleware";

const subjectService = Container.get(SubjectService);

export const getAllSubjects: Controller = async (_req, res) => {
try {
const subjectsRef = firestore.collection("subjects");
const snapshot = await subjectsRef.get();

const subjects = snapshot.docs.map((doc) => {
return {
id: doc.id,
name: doc.data().name,
iconUrl: doc.data().iconUrl,
};
const subjects = await subjectService.getAllSubjects();
res.json({
status: "success",
data: subjects,
});

res.json({ status: "success", data: subjects });
} catch (error) {
logger.error(`Error when getting all subjects: ${error}`);
res.status(400).json({
status: "fail",
message: "Failed to get all subjects.",
message: "Failed to get all subjects",
});
}
};
16 changes: 16 additions & 0 deletions src/services/subject.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Service } from "typedi";
import { BaseService } from "./base.service";
import type { Subject } from "@/types";

@Service()
export class SubjectService extends BaseService {
async getAllSubjects(): Promise<Subject[]> {
const snapshot = await this.collection("subjects").get();

return snapshot.docs.map((doc) => ({
id: doc.id,
name: doc.data().name,
iconUrl: doc.data().iconUrl,
}));
}
}

0 comments on commit a65ec88

Please sign in to comment.