valoraciones.js 2.55 KB
import EC from 'elliptic'
import { tap } from 'ramda'
import { Buffer } from 'buffer/'
import { BACKEND_URL } from '../../constants'
import { ownPrivate } from '../../constants/keys'

const ec = new EC.ec('secp256k1')
const clientPriv = ec.keyFromPrivate(ownPrivate)

export const VALORACION_REQUESTED = 'VALORACION_REQUESTED'
export const valoracionRequested = () => ({
  type: VALORACION_REQUESTED
})

export const VALORACION_RECEIVED = 'VALORACION_RECEIVED'
export const valoracionReceived = ({ valoracion }) => ({
  type: VALORACION_RECEIVED,
  valoracion,
})

export const VALORACION_FAILED = 'VALORACION_FAILED'
export const valoracionFailed = (error) => ({
  type: VALORACION_FAILED,
  error
})

export const requestValoracion = (id, email) => (dispatch) => {
  dispatch(valoracionRequested())
  const url = `${BACKEND_URL}/valoraciones/solicitud/${id}/usuario/${email}/`
  const options = {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  }

  return fetch(url, options)
    .then(response => response.text())
    .then(tap(text => dispatch({ type: 'TEXT_RECEIVED', text })))
    .then(JSON.parse)
    .then(json => dispatch(valoracionReceived(json)))
    .catch(error => dispatch(valoracionFailed(error)))
}


export const VALORACION_POSTED = 'VALORACION_POSTED'
export const valoracionPosted = (valoracion) => ({
  type: VALORACION_POSTED,
  valoracion
})
export const VALORACION_POST_FAILED = 'VALORACION_POST_FAILED'
export const valoracionPostFailed = () => ({
  type: VALORACION_POST_FAILED
})
export const VALORACION_POST_SUCCESS = 'VALORACION_POST_SUCCESS'
export const valoracionPostSuccess = (result) => ({
  type: VALORACION_POST_SUCCESS,
  result
})


export const postValoracion = (solicitudId, usuario, valoracion) => (dispatch) => {
  dispatch(valoracionPosted(valoracion))
  const message = JSON.stringify({ valoracion, usuario })
  const firma = new Buffer(clientPriv.sign(message).toDER()).toString('hex')

  const options = {
    method: 'POST',
    body: message,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  }


  const url = `${BACKEND_URL}/solicitudes/${solicitudId}/valoracion/${firma}`

  const internal = () => fetch(url, options)
    .then(response => response.text())
    .then(tap(text => dispatch({ type: 'TEXT_RECEIVED', text })))
    .then(JSON.parse)
    .then(json => {
      if (json.error) return dispatch(valoracionPostFailed(json.error))
      return dispatch(valoracionPostSuccess(json))
    })
    .catch(error => dispatch(valoracionPostFailed(error)))
  return internal()
}