nobot-examples icon indicating copy to clipboard operation
nobot-examples copied to clipboard

Part 1 - 018 - Bitly Updates

Open JaimeStill opened this issue 6 years ago • 0 comments

The bitly API has changed a bit since this was published. Please find the revised solution for shorten-url.js.

Note - Version of bitly npm package is ^6.0.8

Changes

  • Bitly is now BitlyClient, so the require statement has changed.
  • bitly no longer returns the status_code or status_text properties in the object that it returns.
    • If the .shorten(longUrl) call doesn't properly resolve, as far as I can tell, it just goes throws an error and the promise is rejected.

bitly-response

bitly response object

shorten-url.js

const { BitlyClient } = require('bitly');
const { BITLY_TOKEN } = require('./config');

const bitly = new BitlyClient(BITLY_TOKEN);

const args = process.argv.slice(2);
const [urlToShorten] = args;

const expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi;

const regex = new RegExp(expression);

if (urlToShorten === undefined || urlToShorten.match(regex) === null) {
    console.log("Please pass a string in URL form, e.g. 'https://github.com'");
    process.exit(0);
}

bitly.shorten(urlToShorten)
    .then((response) => {
        if (response.url) {
            console.log(`Shortened URL is: ${response.url}`);
        }
    })
    .catch((err) => {
        console.error(err);
    });

JaimeStill avatar Aug 12 '18 03:08 JaimeStill