OSDN Git Service

updated account alias.
[bytom/bytom-electron.git] / src / features / mockhsm / actions.js
1 import { baseListActions, baseCreateActions, baseUpdateActions } from 'features/shared/actions'
2 import { chainClient } from 'utility/environment'
3 import {push} from 'react-router-redux'
4
5 const type = 'key'
6 const clientApi = () => chainClient().mockHsm.keys
7
8 const list = baseListActions(type, {
9   className: 'Key',
10   clientApi,
11 })
12 const create = baseCreateActions(type, {
13   className: 'Key',
14   clientApi,
15 })
16
17 const update = baseUpdateActions(type, {
18   className: 'Key',
19   clientApi,
20 })
21
22 create.submitForm = (data) => function (dispatch) {
23   if (typeof data.alias == 'string')  data.alias = data.alias.trim()
24
25   return clientApi().create(data)
26     .then((resp) => {
27       if (resp.status === 'fail') {
28         throw resp
29       }
30
31       dispatch({type: 'NEW_KEY', data: resp.data.mnemonic})
32       dispatch( push('/keys/mnemonic') )
33     })
34 }
35
36 const resetPassword = {
37   submitResetForm: (params) => {
38     let promise = Promise.resolve()
39     return (dispatch)  => {
40       return promise.then(() => clientApi().resetPassword(params).then((resp) => {
41         if(resp.data.changed){
42           dispatch({ type: `RESET_PASSWORD_${type.toUpperCase()}`, resp })
43           dispatch(push({
44             pathname: `/${type}s/${params.xpub}`,
45             state: {
46               preserveFlash: true
47             }
48           }))
49         }else{
50           throw {code: 'F_BTM001'}
51         }
52       }))
53     }
54   }
55 }
56
57 const checkPassword = (data) => (dispatch) => {
58   return clientApi().checkPassword(data)
59     .then((resp) => {
60       if(resp.status === 'fail'){
61         throw resp
62       }else if(!resp.data.checkResult){
63         throw {code: 'F_BTM000'}
64       }
65       dispatch({ type: 'KEY_PASSWORD_SUCCESS'})
66     })
67 }
68
69 const createExport =  (arg, fileName) => (dispatch) => {
70   clientApi().export(arg).then(resp => {
71     if(resp.status == 'success'){
72       const privateKey = resp.data.privateKey
73
74       var element = document.createElement('a')
75       element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(privateKey))
76       element.setAttribute('download', fileName)
77       element.style.display = 'none'
78       document.body.appendChild(element)
79       element.click()
80
81       document.body.removeChild(element)
82     }else if(resp.status == 'fail'){
83       dispatch({ type: 'ERROR', payload: {message: resp.msg} })
84     }
85   })
86 }
87
88 const createSuccess = ()=> (dispatch) =>{
89   dispatch(create.created())
90   dispatch(push('/keys'))
91 }
92
93 export default {
94   ...create,
95   ...list,
96   ...update,
97   ...resetPassword,
98   checkPassword,
99   createExport,
100   createSuccess
101 }