From cc692f34c33484c1aa56e66612c578623d749f2d Mon Sep 17 00:00:00 2001 From: Valtteri Kantanen Date: Thu, 18 Jul 2024 17:37:30 +0300 Subject: [PATCH] [Backend] Add null checks to students.ts and add a util function `keysOf` --- services/backend/src/services/students.ts | 2 ++ .../src/services/studyProgramme/studyTrackStats.ts | 3 ++- services/backend/src/util/index.ts | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/services/backend/src/services/students.ts b/services/backend/src/services/students.ts index cf9a8b5937..ababd96d16 100644 --- a/services/backend/src/services/students.ts +++ b/services/backend/src/services/students.ts @@ -91,6 +91,7 @@ const byStudentNumber = async (studentNumber: string) => { }, }), ]) + if (!student) return null const tagprogrammes = await ElementDetail.findAll({ where: { code: { @@ -324,6 +325,7 @@ const formatStudentWithoutTags = ( export const withStudentNumber = async (studentNumber: string) => { try { const student = await byStudentNumber(studentNumber) + if (!student) return null return formatStudent(student) } catch (error) { logger.error(`Error when fetching single student ${error}`) diff --git a/services/backend/src/services/studyProgramme/studyTrackStats.ts b/services/backend/src/services/studyProgramme/studyTrackStats.ts index 433c506e18..4049d6d5f8 100644 --- a/services/backend/src/services/studyProgramme/studyTrackStats.ts +++ b/services/backend/src/services/studyProgramme/studyTrackStats.ts @@ -2,6 +2,7 @@ import moment from 'moment' import { Credit, SISStudyRight, SISStudyRightElement } from '../../models' import { GenderCode, EnrollmentType, ExtentCode } from '../../types' +import { keysOf } from '../../util' import { countTimeCategories } from '../graduationHelpers' import { getSemestersAndYears } from '../semesters' import { getDateOfFirstSemesterPresent } from './studyProgrammeBasics' @@ -375,7 +376,7 @@ const getMainStatsByTrackAndYear = async ( yearlyStats.Total[track] = getEmptyYear() } - for (const field of Object.keys(yearlyStats[year][track]) as Array) { + for (const field of keysOf(yearlyStats[year][track])) { if (field !== 'otherCountriesCounts') { yearlyStats.Total[track][field] += yearlyStats[year][track][field] continue diff --git a/services/backend/src/util/index.ts b/services/backend/src/util/index.ts index 34981c9237..646bdd7959 100644 --- a/services/backend/src/util/index.ts +++ b/services/backend/src/util/index.ts @@ -46,3 +46,11 @@ export const sortByProgrammeCode = (a: string, b: string) => { } return a.localeCompare(b) } + +/** + * Returns the keys of the given object as an array of strings, typed as the keys of the object. + * @param obj The object whose keys are to be returned. + */ +export const keysOf = (obj: T) => { + return Object.keys(obj) as Array +}