Skip to content

Commit

Permalink
added function to set cached algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
KLee954 committed Oct 8, 2024
1 parent c4bf2c5 commit fecb44a
Show file tree
Hide file tree
Showing 25 changed files with 118 additions and 64 deletions.
28 changes: 12 additions & 16 deletions jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,24 +350,20 @@ const mockDataServices: MockDataServices = {
])
),
fetchStudentLpLeAlg: jest.fn(() =>
Promise.resolve(
{
algorithm_id: 1,
id: 1,
short_name: 'studentTest',
student_id: 1,
topic_id: 1
}
)
Promise.resolve({
algorithm_id: 1,
id: 1,
short_name: 'studentTest',
student_id: 1,
topic_id: 1
})
),
fetchTeacherLpLeAlg: jest.fn(() =>
Promise.resolve(
{
algorithm_id: 1,
short_name: 'teacherTest',
topic_id: 1
}
)
Promise.resolve({
algorithm_id: 1,
short_name: 'teacherTest',
topic_id: 1
})
),
postStudentLpLeAlg: jest.fn(() =>
Promise.resolve({
Expand Down
4 changes: 2 additions & 2 deletions src/common/hooks/University/University.hooks.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import log from 'loglevel'
import { usePersistedStore } from '@store'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useState, useEffect, useMemo } from 'react'
import { usePersistedStore } from '@store'

export type UniversityHookReturn = {
readonly university: string
Expand Down
1 change: 1 addition & 0 deletions src/common/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { HaskiTheme } from './Theme/HaskiTheme'
import { Theme } from './Theme/Theme'
import { reportWebVitals, sendToAnalytics } from './Webvitals/Webvitals'

export { reportWebVitals, sendToAnalytics, Theme, HaskiTheme }
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useContext } from 'react'
import { SnackbarContext, postStudentLpLeAlg, postTeacherLpLeAlg } from '@services'
import { usePersistedStore } from '@store'
import { usePersistedStore, useStore } from '@store'

/**
*
Expand All @@ -25,6 +25,8 @@ export type useAlgorithmSettingsModalHookParams = {
const useAlgorithmSettingsModal = (params: useAlgorithmSettingsModalHookParams) => {
const { addSnackbar } = useContext(SnackbarContext)
const getUser = usePersistedStore.getState().getUser
const setStudentLpLeAlgorithm = useStore.getState().setStudentLpLeAlgorithm
const setTeacherLpLeAlgorithm = useStore.getState().setTeacherLpLeAlgorithm

const handleSave = useCallback(() => {
getUser().then((user) => {
Expand All @@ -36,6 +38,7 @@ const useAlgorithmSettingsModal = (params: useAlgorithmSettingsModalHookParams)
params.options[params.selected].key
)
.then(() => {
setTeacherLpLeAlgorithm(params.getIDs.topicID, params.options[params.selected].key)
if (params.changeObserver) params.changeObserver()
})
.catch((error) => {
Expand All @@ -44,6 +47,7 @@ const useAlgorithmSettingsModal = (params: useAlgorithmSettingsModalHookParams)
} else if (user.role === 'student') {
postStudentLpLeAlg(user.settings.user_id, params.getIDs.topicID, params.options[params.selected].key)
.then(() => {
setStudentLpLeAlgorithm(user.settings.user_id, params.getIDs.topicID, params.options[params.selected].key)
if (params.changeObserver) params.changeObserver()
})
.catch((error) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const mockOptions = [
{ name: 'option3', description: 'description3', key: 'key3' }
]


describe('AlgorithmSettingsModal', () => {
it('is displayed with all options', () => {
const open = true
Expand Down
8 changes: 4 additions & 4 deletions src/components/Newsbanner/Newsbanner.hooks.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import i18next from 'i18next'
import log from 'loglevel'
import { useMemo, useState, useContext, useEffect } from 'react'
import { SnackbarContext } from '@services'
import { useSessionStore } from '@store'
import { useContext, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useUniversity } from '@common/hooks'
import i18next from 'i18next'
import { SnackbarContext } from '@services'
import { useSessionStore } from '@store'

/**
* @prop sets the newsItem if there is atleast one news
Expand Down
4 changes: 2 additions & 2 deletions src/components/Newsbanner/Newsbanner.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import '@testing-library/jest-dom'
import { fireEvent, render, act, renderHook } from '@testing-library/react'
import { act, fireEvent, render, renderHook } from '@testing-library/react'
import { mockServices } from 'jest.setup'
import Newsbanner from './Newsbanner'
import { MemoryRouter } from 'react-router-dom'
import { useUniversity } from '@common/hooks'
import Newsbanner from './Newsbanner'

describe('Newsbanner tests', () => {
beforeEach(() => {
Expand Down
6 changes: 3 additions & 3 deletions src/components/Newsbanner/Newsbanner.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { keyframes } from '@emotion/react'
import { memo } from 'react'
import { Alert, Box, Collapse, IconButton, Typography } from '@common/components'
import { Close } from '@common/icons'
import { memo } from 'react'
import { keyframes } from '@emotion/react'
import { NewsbannerHookReturn, useNewsbanner as _useNewsbanner } from './Newsbanner.hooks'
import { useSessionStore } from '@store'
import { NewsbannerHookReturn, useNewsbanner as _useNewsbanner } from './Newsbanner.hooks'

export type NewsbannerProps = {
useNewsbanner?: () => NewsbannerHookReturn
Expand Down
2 changes: 1 addition & 1 deletion src/components/PrivacyModal/PrivacyModal.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import '@testing-library/jest-dom'
import { fireEvent, render, act } from '@testing-library/react'
import { act, fireEvent, render } from '@testing-library/react'
import { mockServices } from 'jest.setup'
import * as router from 'react-router'
import { MemoryRouter } from 'react-router-dom'
Expand Down
2 changes: 1 addition & 1 deletion src/components/PrivacyModal/PrivacyModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {
Tooltip,
Typography
} from '@common/components'
import { PrivacyModalHookReturn, usePrivacyModal as _usePrivacyModal } from './PrivacyModal.hooks'
import { useUniversity } from '@common/hooks'
import { PrivacyModalHookReturn, usePrivacyModal as _usePrivacyModal } from './PrivacyModal.hooks'

const style = {
position: 'absolute',
Expand Down
4 changes: 2 additions & 2 deletions src/components/TopicCard/TopicCard.hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const useTopicCard = (params: TopicCardHookParams) => {

const changeObserver = useCallback(() => {
getUser().then((user) => {
getStudentAlgorithm(true, user.settings.user_id, params.topic?.id)
getStudentAlgorithm(user.settings.user_id, params.topic?.id)
.then((res) => {
setStudentSelection(res.short_name)
})
Expand All @@ -75,7 +75,7 @@ export const useTopicCard = (params: TopicCardHookParams) => {

useEffect(() => {
getUser().then((user) => {
getStudentAlgorithm(false, user.settings.user_id, params.topic?.id)
getStudentAlgorithm(user.settings.user_id, params.topic?.id)
.then((res) => {
setStudentSelection(res.short_name)
})
Expand Down
12 changes: 6 additions & 6 deletions src/components/TopicCard/TopicCard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ describe('TopicCard tests', () => {
await waitFor(() => {
expect(queryByText('components.TopicCard.learningPath')).toBeInTheDocument
expect(queryByText('components.TopicCard.studentTest')).toBeInTheDocument
expect(mockServices.fetchStudentLpLeAlg).toHaveBeenCalledTimes(2)
expect(mockServices.fetchStudentLpLeAlg).toHaveBeenCalledTimes(1)
})
})

Expand Down Expand Up @@ -292,7 +292,7 @@ describe('TopicCard tests', () => {
})
)

mockServices.fetchStudentLpLeAlg = jest
mockServices.fetchStudentLpLeAlg = jest
.fn()
.mockRejectedValueOnce(new Error('Error'))
.mockRejectedValueOnce(new Error('Error'))
Expand Down Expand Up @@ -383,12 +383,12 @@ describe('TopicCard tests', () => {
},
university: 'TH-AB'
})
)
)

mockServices.fetchStudentLpLeAlg = jest
.fn()
.mockRejectedValueOnce(new Error('Error'))
.mockRejectedValueOnce(new Error('Error'))
.fn()
.mockRejectedValueOnce(new Error('Error'))
.mockRejectedValueOnce(new Error('Error'))

const { queryByText } = render(
<MemoryRouter>
Expand Down
8 changes: 1 addition & 7 deletions src/core/LearningPathAlgorithm/StudentLpLeAlgorithm.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
type StudentLpLeAlgorithmReturn = (
ignoreCache: boolean,
userId?: number,
topicId?: number
) => Promise<StudentLpLeAlgorithm>
type StudentLpLeAlgorithmReturn = (userId?: number, topicId?: number) => Promise<StudentLpLeAlgorithm>

type StudentLpLeAlgorithm = {
algorithm_id: number
id: number
short_name: string
student_id: number
topic_id: number
Expand Down
2 changes: 1 addition & 1 deletion src/core/LearningPathAlgorithm/TeacherLpLeAlgorithm.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
type TeacherLpLeAlgorithmReturn = (topicId?: number) => Promise<TeacherLpLeAlgorithm>

type TeacherLpLeAlgorithm = {
algorithm_id: number
algorithm_id?: number
short_name: string
topic_id: number
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ import LearningPathElement from './LearningPathElement/LearningPathElement'
import LearningPathElementStatus from './LearningPathElement/LearningPathElementStatus'
import LearningPathLearningElement from './LearningPathLearningElement/LearningPathLearningElement'
import LearningPathTopic from './LearningPathTopic/LearningPathTopic'
import News, { NewsResponse } from './News/News'
import ILS from './QuestionnaireResults/ILS'
import ListK from './QuestionnaireResults/ListK'
import News, { NewsResponse } from './News/News'
import StudentLearningElement from './StudentLearningElement/StudentLearningElement'
import Topic from './Topic/Topic'
import User from './User/User'
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Contact/Contact.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useContext } from 'react'
import { useContext, useState } from 'react'
import { ContactForm } from '@components'
import { AuthContext } from '@services'
import { ContactHookProps, ContactHookReturn, useContact as _useContact } from './Contact.hooks'
Expand Down
4 changes: 2 additions & 2 deletions src/pages/MainFrame/MainFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import {
Footer,
LocalNavBar,
MenuBar,
Newsbanner,
OpenQuestionnaire,
PrivacyModal,
Newsbanner
PrivacyModal
} from '@components'

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ import { fetchData } from '../RequestResponse'
* @category Services
*/

export const fetchStudentLpLeAlg: StudentLpLeAlgorithmReturn = async (
ingnoreCache: boolean,
userId?: number,
topicId?: number
) => {
export const fetchStudentLpLeAlg: StudentLpLeAlgorithmReturn = async (userId?: number, topicId?: number) => {
return fetchData<StudentLpLeAlgorithm>(getConfig().BACKEND + `/user/${userId}/topic/${topicId}/studentAlgorithm`, {
method: 'GET',
credentials: 'include',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('fetchStudentLpLeAlg has expected behaviour', () => {
const userId = 1
const topicId = 1

const result = await fetchStudentLpLeAlg(false, userId, topicId)
const result = await fetchStudentLpLeAlg(userId, topicId)

expect(fetch).toHaveBeenCalledWith(`${getConfig().BACKEND}/user/${userId}/topic/${topicId}/studentAlgorithm`, {
method: 'GET',
Expand Down Expand Up @@ -54,7 +54,7 @@ describe('fetchStudentLpLeAlg has expected behaviour', () => {
const userId = 1
const topicId = 1

await expect(fetchStudentLpLeAlg(false, userId, topicId)).rejects.toThrow(expectedMessage)
await expect(fetchStudentLpLeAlg(userId, topicId)).rejects.toThrow(expectedMessage)
})

it('should throw an unknown error when the response does not have an error variable', async () => {
Expand All @@ -70,6 +70,6 @@ describe('fetchStudentLpLeAlg has expected behaviour', () => {
const userId = 1
const topicId = 1

await expect(fetchStudentLpLeAlg(false, userId, topicId)).rejects.toThrow('')
await expect(fetchStudentLpLeAlg(userId, topicId)).rejects.toThrow('')
})
})
2 changes: 1 addition & 1 deletion src/services/News/fetchNews.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NewsResponse } from '@core'
import { getConfig } from '@shared'
import { fetchData } from '../RequestResponse'
import { NewsResponse } from '@core'

/**
*
Expand Down
17 changes: 17 additions & 0 deletions src/store/Slices/StudentLpLeAlgSlice.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import '@testing-library/jest-dom'
import { useStore } from '../Zustand/Store'

describe('StudentLpLeAlgSlice', () => {
test('explicitely setting the algorithm in cache from the frontend', async () => {
const setStudentLpLeAlg = useStore.getState().setStudentLpLeAlgorithm
const getStudentLpLeAlgorithm = useStore.getState().getStudentLpLeAlgorithm
const userId = 1
const topicId = 1
const algorithmName = 'testAlgorithm'

setStudentLpLeAlg(userId, topicId, algorithmName)
const cachedAlgorithm = await getStudentLpLeAlgorithm(userId, topicId)

expect(cachedAlgorithm.short_name).toBe('testAlgorithm')
})
})
22 changes: 19 additions & 3 deletions src/store/Slices/StudentLpLeAlgSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { resetters } from '../Zustand/Store'
export default interface StudentLpLeAlgorithmSlice {
_cache_StudentLpLeAlgorithm_record: Record<string, StudentLpLeAlgorithm>
getStudentLpLeAlgorithm: StudentLpLeAlgorithmReturn
setStudentLpLeAlgorithm: (userId?: number, topicId?: number, algorithmName?: string) => void
}

export const createStudentLpLeAlgorithmSlice: StateCreator<StoreState, [], [], StudentLpLeAlgorithmSlice> = (
Expand All @@ -16,10 +17,10 @@ export const createStudentLpLeAlgorithmSlice: StateCreator<StoreState, [], [], S
resetters.push(() => set({ _cache_StudentLpLeAlgorithm_record: {} }))
return {
_cache_StudentLpLeAlgorithm_record: {},
getStudentLpLeAlgorithm: async (ignoreCache, userId, topicId) => {
getStudentLpLeAlgorithm: async (userId, topicId) => {
const cached = get()._cache_StudentLpLeAlgorithm_record[`${userId}-${topicId}`]
if (!cached || ignoreCache) {
const studentLpLeAlgorithmResponse = await fetchStudentLpLeAlg(ignoreCache, userId, topicId)
if (!cached) {
const studentLpLeAlgorithmResponse = await fetchStudentLpLeAlg(userId, topicId)
set({
_cache_StudentLpLeAlgorithm_record: {
...get()._cache_StudentLpLeAlgorithm_record,
Expand All @@ -28,6 +29,21 @@ export const createStudentLpLeAlgorithmSlice: StateCreator<StoreState, [], [], S
})
return studentLpLeAlgorithmResponse
} else return cached
},
setStudentLpLeAlgorithm: (userId, topicId, algorithmName) => {
if (userId && topicId && algorithmName) {
const updatedState = {
short_name: algorithmName,
student_id: userId,
topic_id: topicId
}
set({
_cache_StudentLpLeAlgorithm_record: {
...get()._cache_StudentLpLeAlgorithm_record,
[`${userId}-${topicId}`]: updatedState
}
})
}
}
}
}
16 changes: 16 additions & 0 deletions src/store/Slices/TeacherLpLeAlgorithmSlice.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import '@testing-library/jest-dom'
import { useStore } from '../Zustand/Store'

describe('TeacherLpLeAlgSlice', () => {
test('explicitely setting the algorithm in cache from the frontend', async () => {
const setTeacherLpLeAlg = useStore.getState().setTeacherLpLeAlgorithm
const getTeacherLpLeAlgorithm = useStore.getState().getTeacherLpLeAlgorithm
const topicId = 1
const algorithmName = 'testAlgorithm'

setTeacherLpLeAlg(topicId, algorithmName)
const cachedAlgorithm = await getTeacherLpLeAlgorithm(topicId)

expect(cachedAlgorithm.short_name).toBe('testAlgorithm')
})
})
Loading

0 comments on commit fecb44a

Please sign in to comment.