# All files / src/_hooks useFileUploader.tsx

98.88% Statements 89/90
95% Branches 38/40
100% Functions 21/21
100% Lines 68/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    2473x
    3x
    3x

    3x
    3x

    6x
    3x
    3x
    3x

    3x
    10x
    20x

    3x

    15x
    12x
    12x
    12x
    12x
    12x
    12x

    12x
    1x

    11x

    7x

    14x
    7x

    7x
    10x

    10x
    10x

    7x
    14x

    7x
    6x
    12x
    12x
    6x

    14x
    14x

    14x

    14x
    14x

    10x

    10x

    4x

    14x

    7x

    14x
    7x

    7x

    8x
    8x

    8x

    10x
    10x
    10x
    10x
    10x

    10x

    10x
    10x
    10x
    10x

    10x

    5x
    5x

    8x

    2x

     import axios, { Method } from 'axios'
    import { isFunction } from 'formik'
    import { runInQueue } from '../_utils/runInQueue'
    export type UNSAFE_GetEndpoint = (file: File) => string
    export type GetMethod = (file: File) => Method
    export type GetPayload = (file: File) => FormData
    export type UNSAFE_GetPayloadKey = (file: File) => string
    export type GetHeaders = (file: File) => Record<string, string>
    type UploadTargetId = string | number

    type UploadTarget = {
      id: UploadTargetId
      blob: File
    }

    interface UploadFileCallbacks {
      /**
       * @since 10.19.0
       */
      onProgress: (progress: number) => void
      /**
       * @since 10.19.0
       */
      onSuccess: (response: unknown) => void
      /**
       * @since 10.19.0
       */
      onError: (error: unknown) => void
    }

    export interface UNSAFE_UploadFile {
      (file: File, callbacks: UploadFileCallbacks): void
    }

    export interface FileUploaderProps {
      /**
       * @since 10.19.0
       */
      getEndpoint?: UNSAFE_GetEndpoint
      /**
       * @since 10.19.0
       */
      getMethod?: GetMethod
      /**
       * @since 10.19.0
       */
      getPayload?: GetPayload
      /**
       * @since 10.19.0
       */
      getPayloadKey?: UNSAFE_GetPayloadKey
      /**
       * @since 10.19.0
       */
      getHeaders?: GetHeaders
      /**
       * @since 10.19.0
       */
      uploadFile?: UNSAFE_UploadFile
    }

    export interface FileUploader {
      /**
       * @since 10.19.0
       */
      uploadFiles: (
        files: UploadTarget[],
        {
          onCompleteAll,
          onComplete,
          onError,
          onProgress,
        }: {
          onCompleteAll?: () => void
          onComplete?: (fileId: UploadTargetId, response: unknown) => void
          onError?: (fileId: UploadTargetId, error: unknown) => void
          onProgress?: (fileId: UploadTargetId, progress: number) => void
        }
      ) => void
    }
    // max number of concurrent connections in most modern browsers
    const maxConcurrentUpload = 6
    const progressUpdateInterval = 750

    function coroutine(generatorFunction: any) {
      return function (...args: any[]) {
        let generatorObject = generatorFunction(...args)
        generatorObject.next()
        return generatorObject
      }
    }

    async function* uploadQueue() {
      let uploadProcess = () => Promise.resolve()
      while (Itrue) {
        uploadProcess = yield await uploadProcess()
      }
    }

    type Progress = {
      progress: number
      done: boolean
    }

    const queue = coroutine(uploadQueue)()

    export function useFileUploader({
      getEndpoint: externalGetEndpoint,
      getMethod,
      getPayload,
      getPayloadKey,
      getHeaders,
      uploadFile,
    }: FileUploaderProps): FileUploader {
      if (!externalGetEndpoint && !uploadFile) {
        throw new Error(
          'FileSelect.LocalSource: neither "getEndpoint" nor "uploadFile" is defined'
        )
      }

      return {
        uploadFiles: async (
          files,
          { onCompleteAll, onComplete, onError, onProgress }
        ) => {
          await queue.next(async () => {
            const uploadProgressState = new Map<UploadTarget['id'], Progress>()

            const updateProgress = (id: UploadTarget['id'], progress: number) => {
              const isCompleted = uploadProgressState.get(id)?.done || false

              if (!isCompleted) {
                uploadProgressState.set(id, {
                  progress,
                  done: isCompleted,
                })
              }
            }
            const completeProgressUpdate = (fileId: UploadTarget['id']) => {
              uploadProgressState.set(fileId, {
                progress: 100,
                done: true,
              })
            }

            const notifyProgress = () => {
              if (isFunction(onProgress)) {
                uploadProgressState.forEach(({ progress, done }, fileId) => {
                  if (!done) {
                    onProgress(fileId, progress)
                  }
                })
              }
            }

            const upload = async (file: UploadTarget) => {
              const getEndpoint = externalGetEndpoint!

              const execFileUpload =
                uploadFile ??
                uploadFileViaNetwork.bind(null, {
                  getEndpoint,
                  getMethod,
                  getPayload,
                  getPayloadKey,
                  getHeaders,
                })
              try {
                const response = await new Promise<unknown>((resolve, reject) => {
                  execFileUpload(file.blob, {
                    onSuccess: resolve,
                    onProgress: (progress: number) => {
                      updateProgress(file.id, progress)
                    },
                    onError: reject,
                  })
                })
                onComplete?.(file.id, response)
              } catch (err) {
                onError?.(file.id, err)
              } finally {
                completeProgressUpdate(file.id)
              }
            }

            // batch progress bar updates for better performance
            const progressNotifierId = setInterval(
              notifyProgress,
              progressUpdateInterval
            )
            await Promise.all(runInQueue(files, upload, maxConcurrentUpload))
            clearInterval(progressNotifierId)

            onCompleteAll?.()
          })
        },
      }
    }

    function getDefaultPayload(key: string, file: File) {
      const payload = new FormData()
      payload.append(key, file)

      return payload
    }

    async function uploadFileViaNetwork(
      {
        getEndpoint,
        getMethod = () => 'POST',
        getHeaders = () => ({}),
        getPayload,
        getPayloadKey = () => 'file',
      }: {
        getEndpoint: UNSAFE_GetEndpoint
        getMethod?: GetMethod
        getPayload?: GetPayload
        getPayloadKey?: UNSAFE_GetPayloadKey
        getHeaders?: GetHeaders
      },
      file: File,
      { onProgress, onSuccess, onError }: UploadFileCallbacks
    ) {
      const endpoint = getEndpoint(file)
      const method = getMethod(file)
      const headers = getHeaders(file)
      const payload = isFunction(getPayload)
        ? getPayload(file)
        : getDefaultPayload(getPayloadKey(file), file)

      try {
        const response = await axios({
          url: endpoint,
          method,
          data: payload,
          headers,
          onUploadProgress: (e) => {
            const progress = Math.floor((e.loaded / e.total!) * 100)
            onProgress(progress)
          },
        })
        onSuccess(response.data)
      } catch (err) {
        onError(err)
      }
    }