valoraciones.js
2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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()
}