Ben Lin
2024-06-18 ebbd788fbb2c0b45d4473798efc57eec8ba74a25
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { reactive } from 'vue';
 
import type { FetchState, PluginReturn, Service, Subscribe, UseRequestOptions } from './types';
import { isFunction } from './utils/isFunction';
 
export default class Fetch<TData, TParams extends any[]> {
  pluginImpls: PluginReturn<TData, TParams>[] = [];
 
  count: number = 0;
 
  state: FetchState<TData, TParams> = reactive({
    loading: false,
    params: undefined,
    data: undefined,
    error: undefined,
  });
 
  constructor(
    public serviceRef: Service<TData, TParams>,
    public options: UseRequestOptions<TData, TParams>,
    public subscribe: Subscribe,
    public initState: Partial<FetchState<TData, TParams>> = {},
  ) {
    this.setState({ loading: !options.manual, ...initState });
  }
 
  setState(s: Partial<FetchState<TData, TParams>> = {}) {
    Object.assign(this.state, s);
    this.subscribe();
  }
 
  runPluginHandler(event: keyof PluginReturn<TData, TParams>, ...rest: any[]) {
    // @ts-ignore
    const r = this.pluginImpls.map((i) => i[event]?.(...rest)).filter(Boolean);
    return Object.assign({}, ...r);
  }
 
  async runAsync(...params: TParams): Promise<TData> {
    this.count += 1;
    const currentCount = this.count;
 
    const {
      stopNow = false,
      returnNow = false,
      ...state
    } = this.runPluginHandler('onBefore', params);
 
    // stop request
    if (stopNow) {
      return new Promise(() => {});
    }
 
    this.setState({
      loading: true,
      params,
      ...state,
    });
 
    // return now
    if (returnNow) {
      return Promise.resolve(state.data);
    }
 
    this.options.onBefore?.(params);
 
    try {
      // replace service
      let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef, params);
 
      if (!servicePromise) {
        servicePromise = this.serviceRef(...params);
      }
 
      const res = await servicePromise;
 
      if (currentCount !== this.count) {
        // prevent run.then when request is canceled
        return new Promise(() => {});
      }
 
      // const formattedResult = this.options.formatResultRef.current ? this.options.formatResultRef.current(res) : res;
 
      this.setState({ data: res, error: undefined, loading: false });
 
      this.options.onSuccess?.(res, params);
      this.runPluginHandler('onSuccess', res, params);
 
      this.options.onFinally?.(params, res, undefined);
 
      if (currentCount === this.count) {
        this.runPluginHandler('onFinally', params, res, undefined);
      }
 
      return res;
    } catch (error) {
      if (currentCount !== this.count) {
        // prevent run.then when request is canceled
        return new Promise(() => {});
      }
 
      this.setState({ error, loading: false });
 
      this.options.onError?.(error, params);
      this.runPluginHandler('onError', error, params);
 
      this.options.onFinally?.(params, undefined, error);
 
      if (currentCount === this.count) {
        this.runPluginHandler('onFinally', params, undefined, error);
      }
 
      throw error;
    }
  }
 
  run(...params: TParams) {
    this.runAsync(...params).catch((error) => {
      if (!this.options.onError) {
        console.error(error);
      }
    });
  }
 
  cancel() {
    this.count += 1;
    this.setState({ loading: false });
 
    this.runPluginHandler('onCancel');
  }
 
  refresh() {
    // @ts-ignore
    this.run(...(this.state.params || []));
  }
 
  refreshAsync() {
    // @ts-ignore
    return this.runAsync(...(this.state.params || []));
  }
 
  mutate(data?: TData | ((oldData?: TData) => TData | undefined)) {
    const targetData = isFunction(data) ? data(this.state.data) : data;
    this.runPluginHandler('onMutate', targetData);
    this.setState({ data: targetData });
  }
}