import { get } from 'lodash' import { create, remove, 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 addAuthor = (author, collectionId, fragmentId) => dispatch => { dispatch(authorRequest()) return create(`/collections/${collectionId}/fragments/${fragmentId}/users`, { email: author.email, role: 'author', ...author, }).then(author => { dispatch(authorSuccess()) return author }, handleError(authorFailure, dispatch)) } export const deleteAuthor = (collectionId, fragmentId, userId) => dispatch => { dispatch(authorRequest()) return remove( `/collections/${collectionId}/fragments/${fragmentId}/users/${userId}`, ) .then(() => dispatch(authorSuccess())) .catch(handleError(authorFailure, dispatch)) } // selectors export const getFragmentAuthors = (state, fragmentId) => get(state, `authors.${fragmentId}`, []) export const getAuthorFetching = state => get(state, 'authors.isFetching', false) export const getAuthorError = state => get(state, 'authors.error', null) 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 } }