import { CalendarItem, Classmate, EtjanstChild, MenuItem, NewsItem, Notification, ScheduleItem, Skola24Child, TimetableEntry, User, } from '@skolplattformen/api-skolplattformen' import { EntityName, EntityReducer, EntityState } from './types' const createReducer = (entity: EntityName): EntityReducer => { const reducer: EntityReducer = (state = {}, action) => { if (action.entity !== entity || !action.extra) return state const key = action.extra?.key const node = state[key] || { status: 'pending', data: action.extra.defaultValue, } let newNode: EntityState switch (action.type) { case 'GET_FROM_API': { newNode = { ...node, error: undefined, status: 'loading', } break } case 'RESULT_FROM_API': { newNode = { ...node, data: action.data || node.data, status: 'loaded', } break } case 'API_ERROR': { newNode = { ...node, status: action.extra.retries < 3 ? node.status : 'error', error: action.error, } break } case 'RESULT_FROM_CACHE': { newNode = { ...node, data: action.data || node.data, } break } default: { newNode = { ...node } } } return { ...state, [key]: newNode, } } return reducer } export const user = createReducer('USER') export const etjanstChildren = createReducer('ETJANST_CHILDREN') export const skola24Children = createReducer('SKOLA24_CHILDREN') export const calendar = createReducer('CALENDAR') export const classmates = createReducer('CLASSMATES') export const menu = createReducer('MENU') export const news = createReducer('NEWS') export const newsDetails = createReducer('NEWS_DETAILS') export const notifications = createReducer('NOTIFICATIONS') export const schedule = createReducer('SCHEDULE') export const timetable = createReducer('TIMETABLE')