Error capturing response from TinyURL's shorten method

204 Views Asked by At

I need to capture the return of the shorten method from the TinyUrl library. I'm trying to store this return in the shortUrl variable and then save it in the database as follows:

import TinyUrl from 'tinyurl';

let shortUrl = '';

    TinyUrl.shorten(req.body.url, function (response, error) {
      if (error) console.log(error);
      console.log(response);
      shortUrl = response;
    });

    // Tudo certo para CRIAR o Site
    const { id, hits, url, short_url } = await Site.create({
      hits: 0,
      url: req.body.url,
      short_url: shortUrl,
    });

    return res.json({
      id,
      hits,
      url,
      short_url,
    });

When viewing console.log(response); the desired return is displayed correctly, but the shortUrl variable is not set. How can I do it ?

1

There are 1 best solutions below

0
Raphael Prado de Oliveira On BEST ANSWER

I implemented it as follows:

const shortUrl = await TinyUrl.shorten(req.body.url);

const { id, hits, url, short_url } = await Site.create({
  hits: 0,
  url: req.body.url,
  short_url: shortUrl,
});