Code Monkey home page Code Monkey logo

node-bitly's Introduction

node-bitly - Unofficial Bitly API for nodejs

CircleCI NPM version Dependencies

V6.x.x to V7.x.x transition - aka V3 of Bitly API to V4 - Breaking Changes

In March 2020, Bitly deprecated the v3 of their API, and switched to v4. Unfortunately, even with the changes to this package to make it compatible, there are several unavoidable breaking changes. These are summarized below:

  • Endpoints no longer support bulk options (multiple hashes or URLs in a single request)
    • Most importantly, this affects expand() and shorten()
    • As a general rule of thumb, none of the v4 endpoints take bulk inputs
  • Return types have changed, for multiple endpoints
  • DEPRECATED: The lookup method and corresponding endpoint have been deprecated

With these changes all previous versions of this library are now full deprecated and there is only 1 version starting with v7.0.0

Here is a simple example of how you might have to update your use of node-bitly to account for the change:

// Both versions
const BitlyClient = require('bitly').BitlyClient;
const bitly = new BitlyClient('<accessToken>');

// v6.1.0
async function example(url) {
  const response = await bitly.shorten(url);
  console.log(`Your shortened bitlink is ${response.url}`);
}
// v7.x.x
async function example(url) {
  const response = await bitly.shorten(url);
  console.log(`Your shortened bitlink is ${response.link}`);
}

Module Features

This module provides calls to the Bitly API for Nodejs.

For more information on the API request and responses visit the Bitly API docs

node-bitly is programmed with TypeScript but is compiled to JavaScript and supports node >= 10.0.0. When you import the client you get full type information. There maybe be some gaps in the information but this will be filled in, in future releases.

Installation

To install via NPM type the following: npm install bitly

You can also install via git by cloning: git clone https://github.com/tanepiper/node-bitly.git /path/to/bitly

Usage

This library uses the API provided by bitly and requires an OAuth token to use. To get your access token, visit OAuth Apps (under Generic Access Token)

See http://dev.bitly.com for format of returned objects from the API

To see the available libary APIs, you can view the API Documentation offline, or you can view the index here (the generated documentation does not work on Github).

Code

TypeScript / ES6 Imports

import { BitlyClient } from 'bitly';
const bitly = new BitlyClient('<accessToken>', {});

async function init() {
  let result;
  try {
    result = await bitly.shorten('https://github.com/tanepiper/node-bitly');
  } catch (e) {
    throw e;
  }
  return result;
}

init();

When the library throws an error, it should be the error object response from Bitly, but if something has gone wrong with your internet or intermediate requests, it is possible that a generic AxiosError might get returned. You can use an exported Type Guard to narrow the type:

import {BitlyClient, isBitlyErrResponse} from 'bitly';
const bitly = new BitlyClient(process.env.BITLY_API_KEY);
let data: BitlyLink;

try {
  data = await bitly.shorten('http://bit.ly/38XaXKy');
} catch (error) {
  if (isBitlyErrResponse(error)) {
    // Inferred type by TS is `BitlyErrorResponse`
    console.log(`Bitly error: ${error.description}`);
  } else if (error.isAxiosError) {
    // Infererred type is `any`, but you can cast to AxiosError safely
    const axiosError = error as unknown as AxiosError;
    console.log(`AxiosError:`, axiosError.toJSON());
  }
}

JavaScript

const { BitlyClient } = require('bitly');
const bitly = new BitlyClient('<accessToken>', {});

let result;
try {
  result = await bitly.shorten(uri);
} catch(e) {
  throw e;
}
return result;

If you are not using node 8 then you can still use the library with Promise values:

const BitlyClient = require('bitly').BitlyClient;
const bitly = new BitlyClient('<accessToken>');

bitly
  .shorten('https://github.com/tanepiper/node-bitly')
  .then(function(result) {
    console.log(result);
  })
  .catch(function(error) {
    console.error(error);
  });

You can also do raw requests to any Bitly endpoint. With this you need to pass the access token to the method

const BitlyClient = require('bitly').BitlyClient;
const bitly = new BitlyClient('<accessToken>');

try {
  return await bitly.bitlyRequest('link/referrers_by_domain', {
    link: 'https://github.com/tanepiper/node-bitly',
    unit: 'hour',
    timezone: 'Europe/Amsterdam'
  });
} catch(e) {
  throw e;
}

Tests

To run tests type npm test.

The tests use replay, which caches the responses from Bitly under the /fixtures directory, until you edit a test's requests payload. This means you can run the test suite without having a Bitly API key, until you need to edit or add a new test.

Once you need to run tests that can't use a cached response and actually hit Bitly's API, you will need to pass your API key to the tests by having an environment variable BITLY_API_KEY set to the value of your key.

node-bitly's People

Contributors

coaxial avatar ecwyne avatar francois2metz avatar g-ongenae avatar gayanhewa avatar georgetaveras1231 avatar jessefulton avatar raccettura avatar shajanjp avatar specious avatar tanepiper avatar tlugger avatar zephrax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-bitly's Issues

Shortener should call back with error when get 500 error from Bitly

If you call Bitly.shorten, and the api gives you an error, the method calls back with the data:
{ data: [], status_code: 500, status_txt: 'INVALID_URI' }

This happens if for example you pass it a url without a slash at the end.

It should be calling back with an error.

ES6 syntax from README not working

This syntax, as indicated in the README for ES6, does not work in 4.1.1:

bitly.shorten('http://nodejs.org', (response) => {
  console.log(response);
}, (error) => {
  console.log(error);
});

The problem is that the shorten function takes two parameters (longUrl, domain), meaning the function passed in the example above is swallowed by the domain param.

The ES5/.then syntax works fine.

Doesn't work

This POS doesn't work. Hitting the REST API over this. Keep an eye out for a new bit.ly module from nparsons08.

API Key or Access Token?

The docs here say to use an API key. But the bitly dev site just has client ID, client secret and access token. Which is the API key?

This uri always gives 500

I am sending this uri -

http://xyz.com/ByS-58?referenceNo=34C49D14&productId=1&restaurantId=1186&orderType=1

This is my code

return bitlyApi.shorten(requestUrl)
                .then((response) => {
                    logger.info(`[BitlyService] got successful response from bitly for ${JSON.stringify(request)} response: ${JSON.stringify(response)}`);
                    request.bitlyUrl = response.data.url;
                    return resolve(request);
                })
                .catch((error) => {
                    logger.info("[BitlyService] got error from bitly");
                    return reject(error);
                });

This is the response that I get:

{\"data\":[],\"status_code\":500,\"status_txt\":\"INVALID_URI\"}

However when I request this url from my bitly account, it works properly

Minor typo on line 85 of bitly.js

Hi--

First off, thanks for making your bit.ly module available.

There is what I am pretty sure is a small typo on line 85. The code refers to its callback as "callback" but the callback is called "cb" in the function declaration. This causes a runtime error when an API call fails, instead of what you'd expect which is for the error to be quietly passed to the callback.

Just passing that along.

Thanks again,
nate

How to get Branded URL?

In my bit.ly account, I have it setup to use a default branded URL, however using the node library, it's giving me back bit.ly links instead of my branded URL instead. Is there a parameter we should be passing in or is this not currently supported?

Something not working in transpiled version in 4.1.1

, {
key: 'doRequest',
value: function doRequest(requestUri) {
// console.log(requestUri);
return new Promise(function(resolve, reject) {
return fetch(requestUri).then(function(response) {

This tries to fetch an entire object

changing requestUri.href actually works. Not sure what the root of the problem is .

Adding TS files as types is non-standard and prevent uses of it as TS modules

Hello back,
I prepared a PR to fix this issue, I will open it if you agree with this changes.

Current behaviour

Using this module with typescript and "moduleResolution": "node" throws two errors:

The first.

node_modules/bitly/src/lib.ts:2:21 - error TS7016: Could not find a declaration file for module 'request-promise'. '/.../project/node_modules/request-promise/lib/rp.js' implicitly has an 'any' type.
  Try `npm install @types/request-promise` if it exists or add a new declaration (.d.ts) file containing `declare module 'request-promise';`

2 import request from 'request-promise';
                      ~~~~~~~~~~~~~~~~~

This explains because tsc with the node module resolution checks types of imported modules.
However, this module exports the TS code and not the rendered declaration, hence it crawls the whole files and types (which are added as dev deps).

So, I think there are two solutions:

  1. Moving the @types/request-promise to deps;
  2. Generating the declaration files (*.d.ts) instead of using the TS code.

The second.

node_modules/bitly/src/lib.ts:96:28 - error TS2532: Object is possibly 'undefined'.

96     item => (isUri(item) ? result.shortUrl.push(item) : typeof item === 'string' && result.hash.push(item))
                              ~~~~~~~~~~~~~~~

node_modules/bitly/src/lib.ts:96:85 - error TS2532: Object is possibly 'undefined'.

96     item => (isUri(item) ? result.shortUrl.push(item) : typeof item === 'string' && result.hash.push(item))
                                                                                       ~~~~~~~~~~~

I don't know why I still have these two errors, it should have been fixed by adding these lines in #63 :

node-bitly/src/lib.ts

Lines 93 to 94 in acce1a6

result.shortUrl = result.shortUrl || [];
result.hash = result.hash || [];

I think it's due to my tsc configs.

These two error makes me think that the second option is better as such cases cannot happen from pure *.d.ts.

Desired behaviour

Doesn't throw errors of compilation when used as a dependency.

References

In the TS Handbook, the advised way to publish is to use the --declaration flag, which will render the *.d.ts files.

Also, in an old article:

It is recommended to specify ‘files’ in your package.json (or use a .npmignore file) to keep your TypeScript sources outside the actual package that will be submitted to npm. As rule of thumb: *.ts files should be in version control but not in the package, *.d.ts and *.js files should be in the package but not in version control.

Request returned 403: RATE_LIMIT_EXCEEDED"}

I'm trying to generate over +100k shorten URL after 121 url it throws this error :
{"status":500,"message":"[node-bitly] Request returned 403: RATE_LIMIT_EXCEEDED"}.

Is there a way I can generate as much as possible ?

shorten should call /v4/shorten rather than /v4/bitlinks

We provide two endpoints to shorten links with the Bitly API.

/v4/bitlinks allows for more inputs in the POST body but is typically less performant and has a lower rate limit.
/v4/shorten allows for fewer data in the POST body (only long_url *required, group_guid, and domain) and has a higher rate limit.

The shorten function in this package should call 'shorten' rather than 'bitlinks' to help with users facing rate limit issues:

return await this.bitlyRequest('bitlinks', { long_url: longUrl });

Link is being accessed before shortened

Why is that link is being access/open when shortening a link? I am about to use shortened url for verification purposes when user open the link but it seems both Bitly and TinyUrl opens the link during shortening process thus the verification becomes useless and proceed without user action. Is there a way to disable such behavior?

Update npm package

Please update the npm package of node bitly. I can't see the fix I did in the package, so I have to use a clone of my fork.

Thanks!

npm package broken

Hey,

after running "npm install bitly" the library is broken and Bitly returns either a MISSING_ARG_LOGIN or MISSING_ARG_APIKEY error on every access.

Installing straight from the git repository, however, works. As in, just cloning the repo and doing a "npm link".

Cheers,
~Swizec

Please, publish pre-compiled.

Many thanks for the Lib!

In React.JS when trying to build, I get the error:

Failed to minify the code from this file:

        ./node_modules/bitly/dist/bitly.js:37

Read more here: http://bit.ly/2tRViJ9

In link say:

Some third-party packages don't compile their code to ES5 before publishing to npm. This often causes problems in the ecosystem because neither browsers (except for most modern versions) nor some tools currently support all ES6 features. We recommend to publish code on npm as ES5 at least for a few more years.

How to proceed?

Im use this method:

import { BitlyClient } from 'bitly';
const bitly = new BitlyClient('<accessToken>', {});
 
async function init() {
  let result;
  try {
    result = await bitly.shorten('https://github.com/tanepiper/node-bitly');
  } catch (e) {
    throw e;
  }
  return result;
}
 
init();

also this:

const { BitlyClient } = require('bitly');
const bitly = new BitlyClient('<accessToken>', {});
 
let result;
try {
  result = await bitly.shorten(uri);
} catch(e) {
  throw e;
}
return result;

Thank You! =)

Drop node 4 support April 2018

This issue serves as a notification that as of April 2018, node bit.ly will no longer support node 4. Currently it is distributed with support back to es5, while being coded on es7. It will continue to support node 6 until the end of its LTS maintainance period. By dropping support it can target es6 and reduce the number of features needed from core-js.

undefined is not a function

I have installed via npm and copied the code including my oauth token... I get an undefined error:

TypeError: undefined is not a function
at new Bitly (../node_modules/bitly/lib/bitly.js:33:26) 

with the following code:


var Bitly       = require('bitly');
var bitly       = new Bitly('my token');

This is pretty elementary, am I missing something obvious?

Bitly.shorten(...).then is not a function | Node 9.0.0

Trying to run below code and throwing the error - Bitly.shorten(...).then is not a function

const url='myurl';

Bitly.shorten(url)
.then(
results =>{
// Do something with your new, shorter url...
const obj = JSON.parse(results);
//having a global variable is not a good idea
// shorturl= obj.data.url;
console.log("got data:",obj.data.url);
return obj.data.url;
}
)
.then(
shorturl => {
//do something with short url
}
)
.then(
undefined
,reject =>//handle any errors
console.error("Failed:",reject)
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.