import { get } from 'lodash' import { create, remove, update, get as apiGet, } from 'pubsweet-client/src/helpers/api' import { handleError } from './utils' // constants const REQUEST = 'authors/REQUEST' const FAILURE = 'authors/FAILURE' const SUCCESS = 'authors/SUCCESS' // actions export const authorRequest = () => ({ type: REQUEST, }) export const authorFailure = error => ({ type: FAILURE, error, }) export const authorSuccess = () => ({ type: SUCCESS, }) export const getAuthors = (collectionId, fragmentId) => apiGet(`/collections/${collectionId}/fragments/${fragmentId}/users`) export const editAuthor = ( collectionId, fragmentId, userId, body, ) => dispatch => { dispatch(authorRequest()) return update( `/collections/${collectionId}/fragments/${fragmentId}/users/${userId}`, body, ).then( () => getAuthors(collectionId, fragmentId).then(authors => { dispatch(authorSuccess()) return authors }, handleError(authorFailure, dispatch)), handleError(authorFailure, dispatch), ) } export const addAuthor = (author, collectionId, fragmentId) => dispatch => { dispatch(authorRequest()) return create(`/collections/${collectionId}/fragments/${fragmentId}/users`, { email: author.email, role: 'author', ...author, }).then( () => getAuthors(collectionId, fragmentId).then(data => { dispatch(authorSuccess()) return data }, handleError(authorFailure, dispatch)), handleError(authorFailure, dispatch), ) } export const deleteAuthor = (collectionId, fragmentId, userId) => dispatch => { dispatch(authorRequest()) return remove( `/collections/${collectionId}/fragments/${fragmentId}/users/${userId}`, ).catch(handleError(authorFailure, dispatch)) } // selectors export const getFragmentAuthors = (state, fragmentId) => get(state, `authors.${fragmentId}`) || [] export const getAuthorFetching = state => state.authors.isFetching export const getAuthorError = state => state.authors.error const initialState = { isFetching: false, error: null } export default (state = initialState, action) => { switch (action.type) { case 'UPDATE_FRAGMENT_REQUEST': case REQUEST: return { ...initialState, isFetching: true, } case 'UPDATE_FRAGMENT_FAILURE': case FAILURE: return { ...initialState, error: get(JSON.parse(get(action.error, 'response') || {}), 'error'), isFetching: false, } case 'UPDATE_FRAGMENT_SUCCESS': case SUCCESS: return initialState default: return state } }