Skip to content

Instantly share code, notes, and snippets.

@buroz
Forked from dploeger/UnirestAsPromise.ts
Created October 4, 2019 10:10
Show Gist options
  • Save buroz/1b15cd05829004a053ce2fc413a18dc4 to your computer and use it in GitHub Desktop.
Save buroz/1b15cd05829004a053ce2fc413a18dc4 to your computer and use it in GitHub Desktop.
Unirest as Promise (Typescript)
import Bluebird = require('bluebird');
import {UnirestError} from './UnirestError';
/**
* A tool for converting a unirest object into a promise
* @param unirest The unirest instance
* @returns {Bluebird<any>}
*/
export function unirestAsPromise(unirest: any): Bluebird<any> {
return new Bluebird(
(resolve, reject) => {
unirest.end(
(response) => {
if (response.ok) {
resolve(response);
} else {
reject(new UnirestError(response));
}
}
);
}
);
}
/**
* Error communicating
*/
export class UnirestError extends Error {
constructor(response: any) {
super(
`Error ${response.code} received: ${response.rawBody}`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment