Created
September 11, 2017 09:26
-
-
Save dploeger/ddeef232753ed324e78224fdd038c9f2 to your computer and use it in GitHub Desktop.
Unirest as Promise (Typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
); | |
} | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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