Use return value in a .map after performing request.get

So basically, due to the security, I need to convert image (from the url) to the base64.

So far I have two functions. One function is converting the image from the url to the Base64 and the other one is mapping over the database and is replacing the default url to the base64 format. I miss the last piece of the puzzle, how to use the return value from the 1st function in the second one – I want to replace ‘test’ in the second function with the result of conversion from url to base64.

 public async convertUrlToBase64(): Promise<any> {
    const request = require('request').defaults({ encoding: null });

    await request.get(
      'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Ray_and_Maria_Stata_Center_%28MIT%29.JPG/2560px-Ray_and_Maria_Stata_Center_%28MIT%29.JPG',
      function (
        error: any,
        response: { statusCode: number; headers: { [x: string]: string } },
        body: ArrayBuffer | SharedArrayBuffer,
      ) {
        return 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
      },
    );
  }

  public mapUriToBase64(note: any): any {
    return {
      ...note,
      images: note.images.map((image: File) => {
        return {
          ...image,
          uri: 'test',
        };
      }),
    };
  }
}

>Solution :

You basically need to wrap it with the Promise in order to get the returned value from your call.

public convertUrlToBase64(): any {
    const request = require('request').defaults({ encoding: null });

    return new Promise(function (resolve, reject) {
      request.get(
        'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Ray_and_Maria_Stata_Center_%28MIT%29.JPG/2560px-Ray_and_Maria_Stata_Center_%28MIT%29.JPG',
        function (
          error: any,
          response: { statusCode: number; headers: { [x: string]: string } },
          body: ArrayBuffer | SharedArrayBuffer,
        ) {
          const data = 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
          resolve(data);
        },
      );
    });
  }

Leave a Reply