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'
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 })
13 showCreate: push(createPath),
15 submitForm: (data) => {
16 const clientApi = options.clientApi ? options.clientApi() : chainClient()[`${type}s`]
17 let promise = Promise.resolve()
19 if (typeof data.id == 'string') data.id = data.id.trim()
20 if (typeof data.alias == 'string') data.alias = data.alias.trim()
22 const jsonFields = options.jsonFields || []
23 jsonFields.map(fieldName => {
24 data[fieldName] = parseNonblankJSON(data[fieldName])
27 const intFields = options.intFields || []
28 intFields.map(fieldName => {
29 data[fieldName] = parseInt(data[fieldName])
34 data.xpubs.forEach(key => {
35 if (key.type == 'generate') {
38 const alias = (key.value || '').trim()
40 : (data.alias || 'generated') + '-' + uuid.v4()
42 return chainClient().mockHsm.keys.create({alias})
44 data.rootXpubs.push(newKey.xpub)
46 } else if (key.value) {
47 data.rootXpubs.push(key.value)
53 return function(dispatch) {
54 return promise.then(() => clientApi.create(data)
56 if (resp.status === 'fail') {
60 dispatch(created(resp))
62 if (options.createModal) {
63 dispatch(actions.app.showModal(
64 options.createModal(resp),
69 let postCreatePath = listPath
70 if (options.redirectToShow) {
71 postCreatePath = `${postCreatePath}/${resp.data.id}`
75 pathname: postCreatePath,