import { ActionType } from '../action-types'; import { Dispatch } from 'redux'; import { ApiResponse, App, Config, NewApp } from '../../interfaces'; import { AddAppAction, DeleteAppAction, GetAppsAction, PinAppAction, ReorderAppsAction, SortAppsAction, UpdateAppAction, } from '../actions/app'; import axios from 'axios'; import { createNotification } from '.'; export const getApps = () => async (dispatch: Dispatch>) => { dispatch({ type: ActionType.getApps, payload: undefined, }); try { const res = await axios.get>('/api/apps'); dispatch({ type: ActionType.getAppsSuccess, payload: res.data.data, }); } catch (err) { console.log(err); } }; export const pinApp = (app: App) => async (dispatch: Dispatch) => { try { const { id, isPinned, name } = app; const res = await axios.put>(`/api/apps/${id}`, { isPinned: !isPinned, }); const status = isPinned ? 'unpinned from Homescreen' : 'pinned to Homescreen'; createNotification({ title: 'Success', message: `App ${name} ${status}`, }); dispatch({ type: ActionType.pinApp, payload: res.data.data, }); } catch (err) { console.log(err); } }; export const addApp = (formData: NewApp | FormData) => async (dispatch: Dispatch) => { try { const res = await axios.post>('/api/apps', formData); createNotification({ title: 'Success', message: `App added`, }); await dispatch({ type: ActionType.addAppSuccess, payload: res.data.data, }); // Sort apps // dispatch(sortApps()); sortApps(); } catch (err) { console.log(err); } }; export const deleteApp = (id: number) => async (dispatch: Dispatch) => { try { await axios.delete>(`/api/apps/${id}`); createNotification({ title: 'Success', message: 'App deleted', }); dispatch({ type: ActionType.deleteApp, payload: id, }); } catch (err) { console.log(err); } }; export const updateApp = (id: number, formData: NewApp | FormData) => async (dispatch: Dispatch) => { try { const res = await axios.put>( `/api/apps/${id}`, formData ); createNotification({ title: 'Success', message: `App updated`, }); await dispatch({ type: ActionType.updateApp, payload: res.data.data, }); // Sort apps dispatch(sortApps()); } catch (err) { console.log(err); } }; export const reorderApps = (apps: App[]) => async (dispatch: Dispatch) => { interface ReorderQuery { apps: { id: number; orderId: number; }[]; } try { const updateQuery: ReorderQuery = { apps: [] }; apps.forEach((app, index) => updateQuery.apps.push({ id: app.id, orderId: index + 1, }) ); await axios.put>('/api/apps/0/reorder', updateQuery); dispatch({ type: ActionType.reorderApps, payload: apps, }); } catch (err) { console.log(err); } }; export const sortApps = () => async (dispatch: Dispatch) => { try { const res = await axios.get>('/api/config'); dispatch({ type: ActionType.sortApps, payload: res.data.data.useOrdering, }); } catch (err) { console.log(err); } };