Upload Service Usage Explanation

In the given code snippet, the upload method is utilized in a controller to handle file uploads. The uploaded files, along with additional parameters, are passed to the UploadService which then processes and stores the files in a Cloudflare storage.
  async upload(
    @UploadedFiles() files: Array<Express.Multer.File>,  // Extracts uploaded files from the request
    @Body('folder') folder: string,  // Extracts the 'folder' field from the request body
    @Req() req: Request  // The Express request object
  ): Promise<any> {
    // Maps the received files to a format compatible with the UploadService
    const mappedFiles: File[] = ((files as Express.Multer.File[]) || []).map(
      (file) => ({
        name: file.originalname,  // Original name of the file
        type: file.mimetype,  // MIME type of the file
        content: file.buffer,  // Binary data of the file
        size: file.size,  // Size of the file in bytes
        extension: `${file.originalname.split('.').pop()}`,  // File extension
      }),
    );

    // Calls the upload method of the UploadService to handle the file upload.
    // Passes the mapped files, folder name, and user information from the request.
    const filesPaths = await this.uploadService.upload(
      mappedFiles,
      folder,
      req['user'],
    );

    // Optional: Adds a delay of 3 seconds before responding.
    // This line can be removed if not needed.
    await new Promise((resolve) => setTimeout(resolve, 3000));

    // Returns the paths of the uploaded files.
    return filesPaths;
  }

Breakdown:

  1. @UploadedFiles() files: Array<Express.Multer.File>: This decorator extracts the uploaded files from the client request.
  2. @Body('folder') folder: string: Extracts the folder name from the request body where the files should be uploaded.
  3. @Req() req: Request: Captures the entire request object.
  4. const mappedFiles: File[]: Maps the received Express.Multer.File objects to a simplified File object format that’s compatible with the UploadService.
  5. const filesPaths = await this.uploadService.upload(mappedFiles, folder, req['user']): Invokes the upload method of UploadService, passing the mapped files, folder name, and user information from the request. The files are uploaded to Cloudflare storage.
  6. await new Promise((resolve) => setTimeout(resolve, 3000)): Adds a slight delay before responding, this might be to ensure that file processing is completed.
  7. return filesPaths: Returns the paths of the uploaded files to the client.