summaryrefslogtreecommitdiff
path: root/app/client/api/crud.actions.js
blob: 1fcae812634388097cbad6941f12c216b51b2eb9 (plain)
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
import { crud_fetch } from './crud.fetch'
import { as_type } from './crud.types'
import { upload_action } from './crud.upload'

export function crud_actions(type) {
  const fetch_type = crud_fetch(type)
  return [
    'index',
    'show',
    'create',
    'update',
    'destroy',
  ].reduce((lookup, param) => {
    lookup[param] = crud_action(type, param, (q) => fetch_type[param](q))
    return lookup
  }, {
    action: (method, fn) => crud_action(type, method, fn),
    upload: (id, fd) => upload_action(type, id, fd),
  })
}

export const crud_action = (type, method, fn) => q => dispatch => {
  dispatch({ type: as_type(type, method + '_loading') })
  fn(q).then(data => {
    dispatch({ type: as_type(type, method), data })
  }).catch(e => {
    dispatch({ type: as_type(type, method + '_error') })
  })
}