tus / tus-js-client

A pure JavaScript client for the tus resumable upload protocol
https://tus.io/
MIT License
2.12k stars 316 forks source link

How to return response after uploading is finished #719

Closed rizametovd closed 2 months ago

rizametovd commented 2 months ago

Question Is there a way to make a function wrapper for tus.Upload and return a response after uploading is completed?

Basically I'd like to have something like this:

  const tusUpload = (file: File) => {
    const upload = new tus.Upload(file, options);
    upload.start();

    return upload.response
  };

And then use it this way:

  const processLocalFile = async (file: LocalFile, formValues: CreateProjectForm) => {
    const requestPayload = getRequestPayload(formValues);

    const shouldUploadViaTus = isFileTooLarge(file.file.size, 5);

    if (shouldUploadViaTus) {
      const video = await tusUpload(file.file);

      const project = await createProject({
        ...requestPayload,
        video_id: video.id,
      });
      return;
    }

    const video = await uploadVideo({ id: file.id, file: file.file });

    const project = await createProject({
      ...requestPayload,
      video_id: video.id,
    });

    return project.id;
  };

Is that correct way?

  const tusUpload = (file: File) => {
    return new Promise((resolve, reject) => {
      const upload = new tus.Upload(file, {
        endpoint: TUS_ENDPOINT,
        retryDelays: null,
        onError: (e) => {
          reject(e);
        },
        onSuccess: (payload) => {
          resolve(payload.lastResponse.getBody());
        },
      });

      upload.start();
    });
  };

Setup details

Acconut commented 2 months ago

Yes, the promise example is correct. The library currently does not have another API method for waiting for an upload.