Rev 5331 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import { axios } from '../../utils'
import { addNotification } from '../notification/notification.actions'
import { conversationActionTypes } from './conversation.types'
export const sendMessage = (url, message) => {
return (dispatch) => {
const formData = new FormData()
formData.append('message', emojione.toShort(message))
axios
.post(url, formData)
.then(({ data: response }) => {
if (!response.success) {
dispatch(
addNotification({ style: 'danger', msg: 'Ha ocurrido un error' })
)
return
}
dispatch(setNewMessage(response.data))
})
.catch((error) => {
throw new Error(error)
})
.catch((err) =>
dispatch(
addNotification({ style: 'danger', msg: new Error(err).message })
)
)
.finally(() => dispatch(finishLoading()))
}
}
export const getMessages = (url) => {
return (dispatch) => {
dispatch(startLoading())
axios
.get(url)
.then(({ data: response }) => {
if (!response.success) {
dispatch(
addNotification({ style: 'danger', msg: 'Ha ocurrido un error' })
)
return
}
const updatedMessages = [...response.data.items].reverse()
dispatch(setMessages(updatedMessages))
})
.catch((err) => {
const errorMessage = new Error(err).message
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
})
.finally(() => dispatch(finishLoading()))
}
}
export const getMessagesByPage = (url, page = 1) => {
return (dispatch) => {
dispatch(startLoading())
axios
.get(`${url}?page=${page}`)
.then(({ data: response }) => {
if (!response.success) {
dispatch(
addNotification({ style: 'danger', msg: 'Ha ocurrido un error' })
)
return
}
const updatedMessages = [...response.data.items].reverse()
dispatch(setMessages(updatedMessages))
})
.catch((err) => {
const errorMessage = new Error(err).message
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
})
.finally(() => dispatch(finishLoading()))
}
}
export const setNewMessage = (newMessage) => ({
type: conversationActionTypes.SET_NEW_MESSAGE,
payload: newMessage,
})
export const updateMessages = (newMessages) => ({
type: conversationActionTypes.SET_UPDATE_MESSAGES,
payload: newMessages,
})
export const setPage = (messages) => ({
type: conversationActionTypes.SET_MESSAGES,
payload: messages,
})
export const setMessages = (messages) => ({
type: conversationActionTypes.SET_MESSAGES,
payload: messages,
})
export const startLoading = () => ({
type: conversationActionTypes.START_LOADING,
})
export const finishLoading = () => ({
type: conversationActionTypes.FINISH_LOADING,
})