OSDN Git Service

Seperate the RestoreKeystore's react logic.
[bytom/bytom-electron.git] / src / features / initialization / actions.js
1 import { chainClient } from 'utility/environment'
2 import {push} from 'react-router-redux'
3
4 const registerKey = (data) => {
5   return (dispatch) => {
6     if (typeof data.keyAlias == 'string')  data.keyAlias = data.keyAlias.trim()
7
8     const keyData = {
9       'alias': data.keyAlias,
10       'password': data.password
11     }
12
13     return chainClient().mockHsm.keys.create(keyData)
14       .then((resp) => {
15         if (resp.status === 'fail') {
16           throw resp
17         }
18
19         if (typeof data.accountAlias == 'string')  data.accountAlias = data.accountAlias.trim()
20         const accountData = {
21           'root_xpubs':[resp.data.xpub],
22           'quorum':1,
23           'alias': data.accountAlias}
24
25         dispatch({type: 'INIT_ACCOUNT', data: resp.data.mnemonic})
26
27         chainClient().accounts.create(accountData)
28           .then((resp) => {
29             if (resp.status === 'fail') {
30               throw resp
31             }
32
33             if(resp.status === 'success') {
34               dispatch(push('/initialization/mnemonic'))
35             }
36           })
37           .catch((err) => {
38             if (!err.status) {
39               throw err
40             }
41           })
42       })
43       .catch((err) => {
44         if (!err.status) {
45           throw err
46         }
47       })
48   }
49 }
50
51 const restoreKeystore = (data) => {
52   return (dispatch) => {
53     const file = data.file
54
55     return new Promise(function(resolve, reject){
56       const fileReader = new FileReader()
57
58       fileReader.onload = function(e) {
59         const result = JSON.parse(e.target.result)
60         return chainClient().backUp.restore(result)
61           .then(resp => {
62             if (resp.status === 'fail') {
63               reject(resp)
64             }
65             resolve()
66             console.log('success')
67           })
68           .catch((err) => {
69             reject(err) })
70       }
71       fileReader.readAsText(file, 'UTF-8')
72       fileReader.onerror = function(error) { reject(error) }
73     })
74   }
75 }
76
77 let actions = {
78   registerKey,
79   restoreKeystore
80 }
81
82 export default actions