|
| 1 | +import asyncify from 'async/asyncify'; |
| 2 | +import retry from 'async/retry'; |
| 3 | +import assign from 'lodash/assign'; |
| 4 | + |
| 5 | +import { loadFailure, loadSuccess } from './actions'; |
| 6 | +import { isAction } from './utils'; |
| 7 | +import { DEFAULT_OPTIONS } from './constants'; |
| 8 | + |
| 9 | +export default class Task { |
| 10 | + constructor(context, monitoredAction, params = {}) { |
| 11 | + if (!isAction(monitoredAction)) { |
| 12 | + throw new Error('action must be a plain object'); |
| 13 | + } |
| 14 | + |
| 15 | + this.context = assign({}, context, { |
| 16 | + action: monitoredAction, |
| 17 | + }); |
| 18 | + |
| 19 | + this.params = assign({}, { |
| 20 | + success({ action }) { |
| 21 | + throw new Error('success() is not implemented', action.type); |
| 22 | + }, |
| 23 | + error({ action }) { |
| 24 | + throw new Error('error() is not implemented', action.type); |
| 25 | + }, |
| 26 | + loading({ action }) { |
| 27 | + return action; |
| 28 | + }, |
| 29 | + shouldFetch() { |
| 30 | + return true; |
| 31 | + }, |
| 32 | + fetch({ action }) { |
| 33 | + throw new Error('Not implemented', action); |
| 34 | + }, |
| 35 | + }, params); |
| 36 | + } |
| 37 | + |
| 38 | + execute(options = {}, callback) { |
| 39 | + const opts = assign({}, DEFAULT_OPTIONS, options); |
| 40 | + |
| 41 | + const context = this.context; |
| 42 | + const dispatch = context.dispatch; |
| 43 | + const { |
| 44 | + success, |
| 45 | + error, |
| 46 | + loading, |
| 47 | + shouldFetch, |
| 48 | + fetch, |
| 49 | + } = this.params; |
| 50 | + |
| 51 | + const disableInternalAction = options.disableInternalAction; |
| 52 | + |
| 53 | + if (!shouldFetch(context)) { |
| 54 | + callback(null, null); // load nothing |
| 55 | + if (!disableInternalAction) { |
| 56 | + const successAction = loadSuccess(context.action); |
| 57 | + dispatch(successAction); |
| 58 | + } |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + dispatch(loading(context)); |
| 63 | + |
| 64 | + // Retry |
| 65 | + const asyncFetch = asyncify(fetch); |
| 66 | + retry({ |
| 67 | + times: opts.retryTimes, |
| 68 | + interval: opts.retryWait, |
| 69 | + }, (retryCb) => { |
| 70 | + asyncFetch(context, retryCb); |
| 71 | + }, (err, result) => { |
| 72 | + if (err) { |
| 73 | + const errorAction = error(context, err); |
| 74 | + if (!disableInternalAction) { |
| 75 | + dispatch(loadFailure(context.action, err)); |
| 76 | + } |
| 77 | + callback(null, dispatch(errorAction)); |
| 78 | + return; |
| 79 | + } |
| 80 | + const successAction = success(context, result); |
| 81 | + callback(null, dispatch(successAction)); |
| 82 | + if (!disableInternalAction) { |
| 83 | + dispatch(loadSuccess(context.action, result)); |
| 84 | + } |
| 85 | + }); |
| 86 | + } |
| 87 | +} |
0 commit comments