Skip to content

Commit fc76766

Browse files
committed
feat: make clean af
1 parent 2e6ef4b commit fc76766

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

src/StudentsController.ts

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import path from "path";
2222
import { PDFDocument, PDFImage } from "pdf-lib";
2323
import qrCodeLib from "qrcode";
2424
import { SchoolFileDTO, Student, StudentAuditLog, StudentAuditLogEntry, StudentDTO, StudentStatus } from "./types";
25+
import { getFileTypeForBuffer } from "./utils/getFiletypeForBuffer";
2526

2627
export class StudentsController {
2728
#studentsCollection: IDatabaseCollection;
@@ -340,21 +341,17 @@ export class StudentsController {
340341
if (schoolLogoBase64 === undefined) return await this.getAssetImage(pdfDoc);
341342

342343
const bytes = Buffer.from(schoolLogoBase64, "base64");
343-
const fistBytesAsHex = bytes.toString("hex", 0, 4);
344-
345-
const pdfMagicBytes = "89504e47";
346-
if (fistBytesAsHex === pdfMagicBytes) {
347-
const schoolLogoImage = await pdfDoc.embedPng(bytes);
348-
return schoolLogoImage;
349-
}
350-
351-
const jpgMagicBytes = "ffd8";
352-
if (fistBytesAsHex.startsWith(jpgMagicBytes)) {
353-
const schoolLogoImage = await pdfDoc.embedJpg(bytes);
354-
return schoolLogoImage;
344+
const filetype = getFileTypeForBuffer(bytes);
345+
if (!filetype) throw new ApplicationError("error.schoolModule.onboardingInvalidLogo", "The logo is not a valid PNG or JPG file. Please check the logo and try again.");
346+
347+
switch (filetype) {
348+
case "png":
349+
const pngImage = await pdfDoc.embedPng(bytes);
350+
return pngImage;
351+
case "jpg":
352+
const jpgImage = await pdfDoc.embedJpg(bytes);
353+
return jpgImage;
355354
}
356-
357-
throw new ApplicationError("error.schoolModule.onboardingInvalidLogo", "The logo is not a valid PNG or JPG file. Please check the logo and try again.");
358355
}
359356

360357
private async getAssetImage(pdfDoc: PDFDocument): Promise<PDFImage | undefined> {

src/utils/getFiletypeForBuffer.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export function getFileTypeForBuffer(buffer: Buffer): "png" | "jpg" | undefined {
2+
const fistBytesAsHex = buffer.toString("hex", 0, 4);
3+
4+
const pngMagicBytes = "89504e47";
5+
if (fistBytesAsHex === pngMagicBytes) return "png";
6+
7+
const jpgMagicBytes = "ffd8";
8+
if (fistBytesAsHex.startsWith(jpgMagicBytes)) return "jpg";
9+
10+
return undefined;
11+
}

0 commit comments

Comments
 (0)