Home > front end >  i want to return a response of an array of image links after uploading to cloudinary in nestjs
i want to return a response of an array of image links after uploading to cloudinary in nestjs

Time:11-23

so i need a way to delay the return statement in the controller until the foreach loop is done. i just need to properly handle the asynchronous operation and i don't know how else

the response returns an empty array because the array is populated after the response is returned

uploads.controller.ts

import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFiles,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadsService } from './uploads.service';
import { v2 as cloudinary } from 'cloudinary';

@Controller('attachments')
export class UploadsController {
  constructor(private readonly uploadsService: UploadsService) {}

  @Post('images')
  @UseInterceptors(FilesInterceptor('attachment'))
  async uploadFile(@UploadedFiles() attachment: Array<Express.Multer.File>) {
    cloudinary.config({
      cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
      api_key: process.env.CLOUDINARY_API_KEY,
      api_secret: process.env.CLOUDINARY_API_SECRET,
      secure: true,
    });
    const response = [];
    await attachment.forEach(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      response.push(fileResponse.secure_url);
      console.log('1', response);
    });
    console.log('2', response);
    return await response;
  }
}

uploads.service.ts

import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary';
import toStream = require('buffer-to-stream');

@Injectable()
export class UploadsService {
  async uploadImage(
    file: Express.Multer.File,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      const upload = v2.uploader.upload_stream((error, result) => {
        if (error) return reject(error);
        resolve(result);
      });

      toStream(file.buffer).pipe(upload);
    });
  }
}

CodePudding user response:

The problem is here.

 await attachment.forEach(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      response.push(fileResponse.secure_url);
      console.log('1', response);
    });

Don't pass async function to Array.forEach. Check out this question.

This will work.

 const response = await Promise.all(attachment.map(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      return fileResponse.secure_url;
    }));
  • Related