// users.ts // Copyright (C) 2020 Dwayne Harris // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see . import { apiFetch } from '../api' import { setEntities } from '../actions/entities' import { startRequest, finishRequest } from '../actions/requests' import { AppThunkAction, Entity, RequestKey, EntityType } from '../types' import { normalize } from '../utils/normalization' export const fetchUser = (id: string): AppThunkAction => { return async dispatch => { dispatch(startRequest(RequestKey.FetchUser)) try { const user = await apiFetch({ path: `/v1/user/${id}` }) const users = normalize([user], EntityType.User) dispatch(setEntities(users.entities)) dispatch(finishRequest(RequestKey.FetchUser, true)) } catch (err) { dispatch(finishRequest(RequestKey.FetchUser, false)) throw err } } } export const subscribe = (id: string): AppThunkAction => { return async dispatch => { dispatch(startRequest(RequestKey.Subscribe)) try { await apiFetch({ path: `/v1/user/${id}/subscribe`, method: 'post', }) dispatch(finishRequest(RequestKey.Subscribe, true)) } catch (err) { dispatch(finishRequest(RequestKey.Subscribe, false)) throw err } } } export const unsubscribe = (id: string): AppThunkAction => { return async dispatch => { dispatch(startRequest(RequestKey.Unsubscribe)) try { await apiFetch({ path: `/v1/user/${id}/unsubscribe`, method: 'post', }) dispatch(finishRequest(RequestKey.Unsubscribe, true)) } catch (err) { dispatch(finishRequest(RequestKey.Unsubscribe, false)) throw err } } }