OSDN Git Service

correct create asset redirection
[bytom/bytom-electron.git] / src / features / shared / actions / create.js
1 import { chainClient } from 'utility/environment'
2 import { parseNonblankJSON } from 'utility/string'
3 import { push } from 'react-router-redux'
4 import actions from 'actions'
5 import uuid from 'uuid'
6
7 export default function(type, options = {}) {
8   const listPath = options.listPath || `/${type}s`
9   const createPath = options.createPath || `${listPath}/create`
10   const created = (param) => ({ type: `CREATED_${type.toUpperCase()}`, param })
11
12   return {
13     showCreate: push(createPath),
14     created,
15     submitForm: (data) => {
16       const clientApi = options.clientApi ? options.clientApi() : chainClient()[`${type}s`]
17       let promise = Promise.resolve()
18
19       if (typeof data.id == 'string')     data.id = data.id.trim()
20       if (typeof data.alias == 'string')  data.alias = data.alias.trim()
21
22       const jsonFields = options.jsonFields || []
23       jsonFields.map(fieldName => {
24         data[fieldName] = parseNonblankJSON(data[fieldName])
25       })
26
27       const intFields = options.intFields || []
28       intFields.map(fieldName => {
29         data[fieldName] = parseInt(data[fieldName])
30       })
31
32       if (data.xpubs) {
33         data.rootXpubs = []
34         data.xpubs.forEach(key => {
35           if (key.type == 'generate') {
36             promise = promise
37               .then(() => {
38                 const alias = (key.value || '').trim()
39                   ? key.value.trim()
40                   : (data.alias || 'generated') + '-' + uuid.v4()
41
42                 return chainClient().mockHsm.keys.create({alias})
43               }).then(newKey => {
44                 data.rootXpubs.push(newKey.xpub)
45               })
46           } else if (key.value) {
47             data.rootXpubs.push(key.value)
48           }
49         })
50         delete data.xpubs
51       }
52
53       return function(dispatch) {
54         return promise.then(() => clientApi.create(data)
55           .then((resp) => {
56             dispatch(created(resp))
57
58             if (options.createModal) {
59               dispatch(actions.app.showModal(
60                 options.createModal(resp),
61                 actions.app.hideModal
62               ))
63             }
64
65             let postCreatePath = listPath
66             if (options.redirectToShow) {
67               postCreatePath = `${postCreatePath}/${resp.data.id}`
68             }
69
70             dispatch(push({
71               pathname: postCreatePath,
72               state: {
73                 preserveFlash: true
74               }
75             }))
76           }))
77       }
78     }
79   }
80 }